Get sum of next 5 to 10 values in a pandas series

Viewed 104

I want to sum up the values of the next 5 to the next 10 values of a pandas series or any list for each element. For example:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
output = [40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 74, 57, 39, 20, 0, 0 ,0 ,0 ,0]

40 being sum of 6,7,8,9,10. I don't really care about the last values as such, they can be nans or sum of the values available suffixed with 0s.

I am aware of the rolling function and have tried :

pd.Series(x).shift(-10).rolling(10, min_periods =1 ).sum()-pd.Series(x).shift(-5).rolling(5, min_periods =1 ).sum()

but it gives the wrong values. It would be a helpful if the answer can be given in terms of variables (5 and 10 be replaced with x,y), but i can figure that out myself too. Please help.

1 Answers

Let's try:

n,m = 5,10
(pd.Series(x).shift(-n, fill_value=0)
   .rolling(n).sum()
   .shift(n-m+1)
)

Output:

0     40.0
1     45.0
2     50.0
3     55.0
4     60.0
5     65.0
6     70.0
7     75.0
8     80.0
9     85.0
10    90.0
11    74.0
12    57.0
13    39.0
14    20.0
15     0.0
16     NaN
17     NaN
18     NaN
19     NaN
dtype: float64
Related