Reputation: 133
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]. Is there a quick hack, specifically using pandas rolling functions, so that it returns the rolling sum from the following 3 indices, i.e. so that the series values are [3, 6, 9, NaN, NaN]?
Upvotes: 1
Views: 612
Reputation: 323396
Adding 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
Upvotes: 1
Reputation: 16434
The only difference is a shift by -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
Upvotes: 3
Reputation: 8641
You need 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
Upvotes: 1