Rolling windows
Rolling windows calculate a statistic over a sliding group of recent values, such as a moving average.
In this page:
Syntax
s.rolling(window=n).mean()
df["column"].rolling(window=n).sum()
Rolling windows
s.rolling(window=3).mean() averages each value with the two before it. The first window-1 results are NaN unless min_periods is set. Rolling also supports sum, std, min and max, and time-based windows like "3D".
Note:
min_periods=1 avoids the initial NaN values.
Example: Rolling windows
import pandas as pd
s = pd.Series([10, 20, 30, 40, 50])
print(s.rolling(3).mean())
print(s.rolling(3, min_periods=1).sum())
print(s.expanding().mean())
# Output:
# 0 NaN
# 1 NaN
# 2 20.0
# 3 30.0
# 4 40.0
# dtype: float64
# 0 10.0
# 1 30.0
# 2 60.0
# 3 90.0
# 4 120.0
# dtype: float64
# 0 10.0
# 1 15.0
# 2 20.0
# 3 25.0
# 4 30.0
# dtype: float64
Related Topics
Common Mistakes
- Forgetting the first values are NaN
- Confusing rolling with expanding
- Using too big a window for short data
Chapter Summary
- rolling slides a window over the data
- First results are NaN by default
- min_periods relaxes that
- Works with mean, sum, std and more
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: