Sub topic 3
Rolling Windows Within Groups
Assume you know pandas groupby, indexed Series, and basic descriptive statistics. A grouped window calculates each window separately, so values from one group never enter another group’s calculation.
Rolling Windows Within Groups
Use groupby before rolling:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 30],
})
df["avg2"] = (
df.groupby("store")["sales"]
.rolling(2)
.mean()
.reset_index(level=0, drop=True)
)
print(df)The first row of each store has NaN because two observations are required. reset_index removes the extra group index so the result aligns with df.
Avoiding Look-Ahead Leakage with `shift`
In forecasting, a feature must use information available before the prediction time. A rolling mean includes the current value, so shift the result by one row:
df["previous_avg3"] = df["sales"].rolling(3).mean().shift(1)The shifted feature at row t uses rows before t. Without shift, the feature can contain information from the value you are trying to predict. For grouped data, apply the shift inside each group.
Custom Window Functions with `apply`
Built-in methods such as mean, sum, and std are usually clearer and faster. Use apply for a statistic pandas does not provide:
s = pd.Series([1, 2, 3, 4, 5, 6])
spread = s.rolling(3).apply(
lambda window: window.max() - window.min(),
raw=True,
)
print(spread)With raw=True, the function receives a NumPy array instead of a pandas Series.
Exponentially Weighted Windows
An exponentially weighted mean, created with ewm, gives more weight to recent observations. Unlike a fixed rolling window, it has no hard boundary where older values suddenly disappear.
recent = s.ewm(span=3, adjust=False).mean()
print(recent)Use rolling windows when a specific recent interval matters. Use ewm when older observations should fade gradually.
Performance Considerations
- Prefer built-in aggregations over
apply. - Select only the columns needed before window operations.
- Sort time-based data once, rather than repeatedly.
- Use a fixed-size window when a row count is sufficient.
- Check grouped results for correct index alignment before assigning them.
Exercise
Why can a rolling feature need shift(1) before being used in a forecast?
Show answer
Because rolling includes the current row by default. Shifting makes the feature use only earlier observations and prevents look-ahead leakage.