首页 > 解决方案 > 将递归函数应用于熊猫数据框列

问题描述

我想根据另一列的功能和当前行之前的行生成一个新列。

IE

NewColumn_{n} = OldColumn_{n} * 0.6 + NewColumn_{n-1} * 0.4

在此处输入图像描述

我有可能不使用就做到这一点iterrows吗?

我看到了这篇文章:如何使用 pandas-python 递归地构造一列数据框?

但我想知道 Pandas 中是否还有其他功能/包或技巧?

purrrR中的东西?

标签: python-3.xpandasdataframerecursion

解决方案


您可以在此处编写自定义函数并使用df.apply

def func(s): # s is `Series`
    newColumn = [0]
    for i, val in enumerate(s):
        newColumn.append(val*0.6 + newColumn[i]*0.4)
    return newColumn[1:]

df['new'] = df[['old']].apply(func) #Don't use df['old'] that would call
                                    #Series.apply which applies func element-wise

   old    new
0    1  0.600
1    2  1.440
2    3  2.376

推荐阅读