简体   繁体   English

索引偏移的熊猫滚动功能

[英]Pandas rolling function with shifted indices

The code 编码

s = pd.Series([0,1,2,3,4])
sr = s.rolling(3)
sr.apply(np.sum)

returns the series with indices [0,1,2,3,4] and values [NaN, NaN, 3, 6, 9]. 返回具有索引[0,1,2,3,4]和值[NaN,NaN,3、6、9]的序列。 Is there a quick hack, specifically using pandas rolling functions, so that it returns the rolling sum from the following 3 indices, ie so that the series values are [3, 6, 9, NaN, NaN]? 是否有快速的技巧, 特别是使用熊猫滚动功能,以便它从以下 3个索引返回滚动总和,即序列值是[3,6,9,NaN,NaN]?

The only difference is a shift by -2: 唯一的区别是移动了-2:

w = 3
s.rolling(w).sum().shift(-w + 1)

0    3.0
1    6.0
2    9.0
3    NaN
4    NaN
dtype: float64

Adding iloc[::-1] 添加iloc[::-1]

s = pd.Series([0,1,2,3,4])
sr = s.iloc[::-1].rolling(3)
sr.sum().iloc[::-1]

0    3.0
1    6.0
2    9.0
3    NaN
4    NaN
dtype: float64

You need numpy.roll() 您需要numpy.roll()

s = pd.Series([0,1,2,3,4])
sr = s.rolling(3)
pd.Series(np.roll(sr.apply(np.sum),3))

Output: 输出:

0    3.0
1    6.0
2    9.0
3    NaN
4    NaN
dtype: float64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM