Left-align a pandas rolling object
This video explains
Left-align a pandas rolling object
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind
--
Chapters
00:00 Question
01:41 Accepted answer (Score 34)
01:56 Answer 2 (Score 4)
02:25 Answer 3 (Score 0)
02:51 Thank you
--
Full question
https://stackoverflow.com/questions/3805...
Accepted answer links:
[shift]: http://pandas.pydata.org/pandas-docs/sta...
Answer 3 links:
[FixedForwardWindowIndexer]: https://pandas.pydata.org/pandas-docs/st...
[.rolling()]: https://pandas.pydata.org/docs/reference...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas
#avk47
Left-align a pandas rolling object
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind
--
Chapters
00:00 Question
01:41 Accepted answer (Score 34)
01:56 Answer 2 (Score 4)
02:25 Answer 3 (Score 0)
02:51 Thank you
--
Full question
https://stackoverflow.com/questions/3805...
Accepted answer links:
[shift]: http://pandas.pydata.org/pandas-docs/sta...
Answer 3 links:
[FixedForwardWindowIndexer]: https://pandas.pydata.org/pandas-docs/st...
[.rolling()]: https://pandas.pydata.org/docs/reference...
--
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