Left-align a pandas rolling object
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities
--
Chapters
00:00 Left-Align A Pandas Rolling Object
01:09 Accepted Answer Score 36
01:22 Answer 2 Score 9
01:44 Answer 3 Score 7
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/3805...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities
--
Chapters
00:00 Left-Align A Pandas Rolling Object
01:09 Accepted Answer Score 36
01:22 Answer 2 Score 9
01:44 Answer 3 Score 7
01:59 Thank you
--
Full question
https://stackoverflow.com/questions/3805...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas
#avk47
ACCEPTED ANSWER
Score 36
I think you can use shift:
a = df.rolling(window=3).mean().shift(-2)
print (a)
A
0 3.666667
1 5.666667
2 11.333333
3 18.333333
4 NaN
5 NaN
ANSWER 2
Score 9
Another solution is to simply reverse the DataFrame/Series before applying the right-aligned rolling window, and re-reverse it afterwards. Something like:
In [1]: df["A"][::-1].rolling(3).mean()[::-1]
Out[1]:
0 3.666667
1 5.666667
2 11.333333
3 18.333333
4 NaN
5 NaN
Name: A, dtype: float64
The benefit over shift is that it should work with variable sized windows in case of time-based windows.
ANSWER 3
Score 7
You can use a FixedForwardWindowIndexer as per the .rolling() docs:
>>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})
>>> df
B
0 0.0
1 1.0
2 2.0
3 NaN
4 4.0
...
>>> indexer = pd.api.indexers.FixedForwardWindowIndexer(window_size=2)
>>> df.rolling(window=indexer, min_periods=1).sum()
B
0 1.0
1 3.0
2 2.0
3 4.0
4 4.0