Search code examples
pythonpandaswindowing

changing position windowing result


The following is the normal result of a rolling window sum:

s = pd.Series(range(5))

s.rolling(window=2).sum()

Out[2]: 
0    NaN
1    1.0
2    3.0
3    5.0
4    7.0
dtype: float64

I, however, would like it to be

Out[2]: 
0    1.0
1    3.0
2    5.0
3    7.0
4    NaN
dtype: float64

How can this be achieved with a rolling window?

Thank you in advance.


Solution

  • Let us make it with shift

    window = 2
    s.rolling(window = window).sum().shift(-window+1)
    Out[270]: 
    0    1.0
    1    3.0
    2    5.0
    3    7.0
    4    NaN
    dtype: float64