给出这样一个数据框df:
id_ val
11111 12
12003 22
88763 19
43721 77
...
我希望为df添加一个列diff,并且它的每一行等于,比方说,该行中的val减去前一行中的diff并乘以0.4然后在前一天添加diff:
diff = (val - diff_prevIoUsDay) * 0.4 + diff_prevIoUsDay
并且第一行中的差异等于该行中的val * 4.也就是说,预期的df应该是:
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)
但得到如错误:
TypeError: (“unsupported operand type(s) for -: ‘float’ and ‘NoneType'”,‘occurred at index 1’)
你知道如何解决这个问题吗?先感谢您!
最佳答案
您可以使用:
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和一个与循环执行相同计算的函数,但在幕后这也是一个循环.