如何使用pandas-python递归构造一列数据框? [英] How to constuct a column of data frame recursively with pandas-python?
问题描述
给出这样一个数据框df
:
id_ val
11111 12
12003 22
88763 19
43721 77
...
我希望在 df
中添加一列 diff
,它的每一行都等于,比如说,该行中的 val
减去前一行的diff
,乘以0.4,再加上前一天的diff
:
I wish to add a column diff
to df
, and each row of it equals to, let's say, the val
in that row minus the diff
in the previous row and multiply 0.4 and then add diff
in the previous day:
diff = (val - diff_previousDay) * 0.4 + diff_previousDay
并且第一行的diff
等于该行的val * 4
.也就是说,预期的 df
应该是:
And the diff
in the first row equals to val * 4
in that row. That is, the expected df
should be:
id_ val diff
11111 12 4.8
12003 22 11.68
88763 19 14.608
43721 77 ...
我已经尝试过:
mul = 0.4
df['diff'] = df.apply(lambda row: (row['val'] - df.loc[row.name, 'diff']) * mul + df.loc[row.name, 'diff'] if int(row.name) > 0 else row['val'] * mul, axis=1)
但是得到了这样的错误:
But got such as error:
TypeError: ("不支持的操作数类型 -: 'float' 和 'NoneType'", 'occurred at index 1')
TypeError: ("unsupported operand type(s) for -: 'float' and 'NoneType'", 'occurred at index 1')
你知道如何解决这个问题吗?提前谢谢你!
Do you know how to solve this problem? Thank you in advance!
推荐答案
您可以使用:
df.loc[0, 'diff'] = df.loc[0, 'val'] * 0.4
for i in range(1, len(df)):
df.loc[i, 'diff'] = (df.loc[i, 'val'] - df.loc[i-1, 'diff']) * 0.4 + df.loc[i-1, 'diff']
print (df)
id_ val diff
0 11111 12 4.8000
1 12003 22 11.6800
2 88763 19 14.6080
3 43721 77 39.5648
计算的迭代性质,其中输入取决于先前步骤的结果,使矢量化变得复杂.您也许可以将 apply 与执行与循环相同的计算的函数一起使用,但在幕后这也将是一个循环.
The iterative nature of the calculation where the inputs depend on results of previous steps complicates vectorization. You could perhaps use apply with a function that does the same calculation as the loop, but behind the scenes this would also be a loop.
这篇关于如何使用pandas-python递归构造一列数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!