Pandas
1 min read
Updated 4 Aug 2026
15. Window Functions
s = pd.Series([1, 2, 3, 4, 5])
s = pd.Series([1, 2, 3, 4, 5])
s.rolling(window=3).mean() # moving average (min 3 obs)
s.rolling(3, min_periods=1).sum() # allow partial windows
s.expanding().mean() # cumulative running mean
s.ewm(span=3).mean() # exponentially weighted mean
# on a DataFrame with dates
df['ma7'] = df['sales'].rolling(7).mean() # 7-day moving average
| Window | Meaning |
|---|---|
rolling(n) |
fixed-size sliding window |
expanding() |
growing window from start (cumulative) |
ewm(span=) |
exponentially weighted (recent obs weigh more) |
💡 Tip:
rolling(7).mean()smooths noisy daily data.ewmreacts faster to recent changes than a simple moving average.
⭐ Interview Question: Rolling vs expanding? Rolling uses the last N observations (fixed window); expanding uses all observations up to the current point (growing window).