【问题标题】:Pandas rolling apply to update the Series for next iteration?熊猫滚动申请更新系列以进行下一次迭代?
【发布时间】:2016-12-08 13:01:26
【问题描述】:

我有以下Series s,我想滚动应用一个自定义函数“test”,并立即将结果更新到s,以便“test”的下一次迭代基于更新的s。让我带你看看我的例子:

s = pd.Series(range(5), index=pd.date_range('1/1/2000', periods=5))
s 
2000-01-01    0
2000-01-02    1
2000-01-03    2
2000-01-04    3
2000-01-05    4
Freq: D, dtype: int32

我的自定义函数如下。这只是我真实案例的简化示例。我们可以看到在第一次迭代中,返回的变量 'update' 设置为 100,我希望将 s 更新为 [0, 1, 100, 3, 4,....]。对于下一次迭代,arr.sum() 将根据 (1+100+3) 而不是 (1+2+3) 计算。

def test(arr):
    print(arr)
    print(arr.sum())
    if arr.sum()%3==0:
        print('True')
        update=100
    else:
        update=arr[-1]
    return update
s=s.rolling(window=3).apply(test)

[ 0.  1.  2.]
3.0
True
[ 1.  2.  3.]
6.0
True
[ 2.  3.  4.]
9.0
True

理想输出:

[ 0.  1.  2.]
3.0
True

'Update s with 100'
[ 1.  100.  3.]
104

[ 100.  3.  4.]
107

【问题讨论】:

    标签: python pandas apply


    【解决方案1】:

    我认为 dataframe.rolling 仅在原始数据帧上运行,它实际上提供了滚动转换。如果在数据帧的滚动窗口中修改了任何数据,则不会在相应的滚动窗口中更新。

    实际上我在这里面临同样的问题。到目前为止,我使用的替代方法是手动循环遍历每个滚动窗口,并将逻辑放入循环中。我知道这很慢,但我不知道是否有更好的方法来做到这一点。

    顺便说一句,其他人也问过同样的问题: Sliding window iterator using rolling in pandas

    Why doesn't my pandas rolling().apply() work when the series contains collections?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-08
      • 2018-12-29
      • 1970-01-01
      • 2021-02-16
      • 2021-09-12
      • 2014-06-13
      • 1970-01-01
      相关资源
      最近更新 更多