在 Python 中转换 R 函数

我有两个变量,由数据框中的数据组成


x = table_1[' Profit ']

y = table_1['diff_date']

其中 x 是


0      820.0

1      306.0

2      139.0

3      105.0

4      140.0

5      149.0

6       96.0

7       80.0

8      124.0

9      102.0

10      72.0

11      54.0

12      66.0

13     124.0

14      64.0

15      93.0

16      58.0

17      59.0

18      62.0

19      65.0

20      74.0

21      67.0

22      80.0

23      91.0

24      81.0

25      56.0

26      43.0

y 是


0       0

1       1

2       2

3       3

4       4

5       5

6       6

7       7

8       8

9       9

10     10

11     11

12     12

13     13

14     14

15     15

16     16

17     17

18     18

19     19

20     20

21     21

22     22

23     23

24     24

25     25

26     26

我在 R 中有一个函数,我试图在 Python 中转换它,除了 R 中的小条件外,我已经完成了大部分任务。


R中的函数是


my_sum <- function(x, y){

  a <- NULL

  for (i in 1:max(y)) {

    a[i] <- sum(x[which(y == (i-1))])

  }

  a[1] <- a[1] - 7000 

  a[2] <- a[2] + 900 

  return(cumsum(a)) 

我想在 Python 中转换这个函数,到目前为止我所做的是


 def my_sum(x,y):

    a = 0

    for i in range (1,max(y)):

       a[i] = sum(x[np.where (y == (i-1))])

                

    a[1] = a[1] - 7000

    a[2] = a[2] + 900

    return(np.cumsum(a))

我不确定的是如何转换sum(x[which(y == (i-1))])为 Python,我已经读过我们可以使用np.where并且我尝试将它转换为类似的东西sum(x[np.where (y == (i-1))])但是它抛出了错误


ValueError:只能使用 MultiIndex 进行元组索引


不确定我的代码中的问题在哪里


jeck猫
浏览 95回答 3
3回答

慕桂英546537

a使用前需要定义:import numpy as npx = np.array([820.0, 306.0, 139.0, 105.0, 140.0])y = np.arange(len(x))def my_sum(x,y):&nbsp; &nbsp; a = np.zeros((len(y),))&nbsp; &nbsp; for i in range (1,max(y)):&nbsp; &nbsp; &nbsp; &nbsp;a[i] = sum(x[np.where(y == (i-1))])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; a[1] = a[1] - 7000&nbsp; &nbsp; a[2] = a[2] + 900&nbsp; &nbsp; return(np.cumsum(a))s = my_sum(x,y)

慕桂英4014372

我不太确定你想要完成什么,虽然看起来你正在做一个分组总和:在 R 中你可以这样做:my_sum1 <- function(x, y){&nbsp; a <- unname(tapply(x, y, sum))&nbsp; a[1:2] <- a[1:2] + c(-7000, 900)&nbsp; cumsum(a)}在 python 中你可以这样做:import numpy as npdef my_sum1(x,y):&nbsp; &nbsp; a = np.array([(x[y == i]).sum() for i in np.unique(y)])&nbsp; &nbsp; a[0:2] = a[0:2] + np.r_[-7000, 900]&nbsp; &nbsp; return a.cumsum()

呼唤远方

def&nbsp;my_sum(x,y): &nbsp;&nbsp;&nbsp;&nbsp;a&nbsp;=&nbsp;[sum(x[np.where(y&nbsp;==&nbsp;(i-1))])&nbsp;for&nbsp;i&nbsp;in&nbsp;range(1,max(y))] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;a[1]&nbsp;-=&nbsp;7000 &nbsp;&nbsp;&nbsp;&nbsp;a[2]&nbsp;+=&nbsp;900 &nbsp;&nbsp;&nbsp;&nbsp;return(np.cumsum(a))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python