【问题标题】:apply a recursive function to a pandas dataframe column将递归函数应用于熊猫数据框列
【发布时间】:2021-02-12 17:20:59
【问题描述】:

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

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

我是否可以不使用iterrows 来做到这一点?

我看到了这个帖子:How to constuct a column of data frame recursively with pandas-python?

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

R 中的 purrr 之类的东西?

【问题讨论】:

    标签: python-3.x pandas dataframe recursion


    【解决方案1】:

    您可以在此处编写自定义函数并使用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
    

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 2017-11-29
      • 1970-01-01
      • 2013-08-10
      相关资源
      最近更新 更多