python - Pandas:累积函数应用

标签 python pandas dataframe

考虑使用 pandas 的简单 dataframe 示例:

df = pd.DataFrame({'x' : [10, 20, 30, 40]}, index = ['0','1','2', '3'])

这给出了以下内容:

index x
0     10
1     20
2     30
3     40

我正在尝试获取 x 的值,并为每一行生成一个结果(通过 lambda),该结果也利用了前一行的计算。也就是说,我想将 y[i+1] 计算为 x[i+1]y[i] 的函数>。例如:

y[i+1] = sin(x[i+1]) + (15 * y[i])

所以这将给出以下 DataFrame:

index x  y
0     10 -0.54
1     20 -7.2
2     30 -109.7
3     40 -1644.7

对于第一行,这大概是一个特例(因为没有 y[-1])?所以我想给它一个具体的数字。

我一直在尝试用 expanding_apply 来解决这个问题,但没有成功。谢谢。

更新

所以我在下面的帮助下(谢谢)以我理解的方式回答了我的问题:

df.loc[:,'y'] = 0
initial_y_val = 10

for i in range (0, df.shape[0]):
    if i == 0 : df.iloc[0,1] = initial_y_val + df.iloc[0,0] 
    else      : df.iloc[i,1] = df.iloc[i,0] + df.iloc[(i-1),1] 

print df

这给出:

    x    y
0  10   20
1  20   40
2  30   70
3  40  110

所以我的问题是,是否有更惯用(更快)的方式来实现相同的结果?

最佳答案

pandas 中的 cumsum 解决了您的问题:

df['y'] = df.x.cumsum()

In [171]: df
Out[171]:
    x    y
0  10   10
1  20   30
2  30   60
3  40  100

编辑:

确实是个很好的问题,通过开发 y1, y2, ...,yn 可以看出它是 sin(x) 的增长多项式,系数为15 的幂。我会通过遍历 DataFrame 索引来选择此解决方案:

z = df.x.map(math.sin)

df['y']=[sum(z[:i]*15**np.arange(int(i)+1)[::-1]) for i,r in df.iterrows()]

In [258]: df
Out[258]:
    x            y
0  10    -0.544021
1  20    -7.247371
2  30  -109.698603
3  40 -1644.733929

关于python - Pandas:累积函数应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32934406/

相关文章:

Python:在 matplot 散点图的 x 轴上绘制字符串会产生 "could not convert string to float"

python - 是否可以就地修改文件中的行?

python - 如何加速 pandas drop() 方法?

python - Pandas :使用转移到数据框

python-3.x - 将两个数据帧相加以获得相等的条目

python - 在 wxPython 中隐藏/删除静态文本

PHP - 如何从 python 程序调用特定函数(Python 3.4、PHP 7、CodeIgniter)

python用逗号将文本分隔到不同的列中

python - Pandas 按层次多重索引分组,不丢失其他索引

python - pandas 1.2.1 to_csv performance with datetime 作为索引并设置 date_format