如何使用pandas-python递归构造一列数据帧? [英] How to constuct a column of data frame recursively with pandas-python?

查看:208
本文介绍了如何使用pandas-python递归构造一列数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出这样的数据帧df:

id_      val     
11111    12
12003    22
88763    19
43721    77
...

我希望将diff列添加到df,并且每一行等于该行中的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) 

但是出现错误:

TypeError :(-不支持的操作数类型:'float'和'NoneType',发生在索引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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆