gpt4 book ai didi

python - 如何前瞻性地使用 Pandas rolling_* 函数

转载 作者:太空狗 更新时间:2023-10-29 17:59:30 25 4
gpt4 key购买 nike

假设我有一个时间序列:

In[138] rng = pd.date_range('1/10/2011', periods=10, freq='D')
In[139] ts = pd.Series(randn(len(rng)), index=rng)
In[140]
Out[140]:
2011-01-10 0
2011-01-11 1
2011-01-12 2
2011-01-13 3
2011-01-14 4
2011-01-15 5
2011-01-16 6
2011-01-17 7
2011-01-18 8
2011-01-19 9
Freq: D, dtype: int64

如果我使用 rolling_* 函数之一,例如 rolling_sum,我可以获得我想要的向后滚动计算的行为:

In [157]: pd.rolling_sum(ts, window=3, min_periods=0)
Out[157]:
2011-01-10 0
2011-01-11 1
2011-01-12 3
2011-01-13 6
2011-01-14 9
2011-01-15 12
2011-01-16 15
2011-01-17 18
2011-01-18 21
2011-01-19 24
Freq: D, dtype: float64

但是如果我想做前瞻性求和呢?我试过这样的事情:

In [161]: pd.rolling_sum(ts.shift(-2, freq='D'), window=3, min_periods=0)
Out[161]:
2011-01-08 0
2011-01-09 1
2011-01-10 3
2011-01-11 6
2011-01-12 9
2011-01-13 12
2011-01-14 15
2011-01-15 18
2011-01-16 21
2011-01-17 24
Freq: D, dtype: float64

但这并不是我想要的行为。我正在寻找的输出是:

2011-01-10    3
2011-01-11 6
2011-01-12 9
2011-01-13 12
2011-01-14 15
2011-01-15 18
2011-01-16 21
2011-01-17 24
2011-01-18 17
2011-01-19 9

即 - 我想要“当前”日加上接下来两天的总和。我目前的解决方案是不够的,因为我关心边缘发生的事情。我知道我可以通过设置两个分别移动 1 天和 2 天的附加列然后对三列求和来手动解决这个问题,但是必须有一个更优雅的解决方案。

最佳答案

为什么不直接在颠倒的系列上做(并颠倒答案):

In [11]: pd.rolling_sum(ts[::-1], window=3, min_periods=0)[::-1]
Out[11]:
2011-01-10 3
2011-01-11 6
2011-01-12 9
2011-01-13 12
2011-01-14 15
2011-01-15 18
2011-01-16 21
2011-01-17 24
2011-01-18 17
2011-01-19 9
Freq: D, dtype: float64

关于python - 如何前瞻性地使用 Pandas rolling_* 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22820292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com