Sub topic 11
Shifted Rolling Statistics
This chapter assumes you know shift() with positive periods, NaN at the edges, groupby().shift(), and the idea of lookahead leakage from the previous chapter. You should also know basic rolling() calls such as rolling(window=3).mean().
Why a plain rolling window leaks
A rolling window ends on the current row by default. The window for 2024-01-03 includes the value from 2024-01-03. If you use that average to predict the value for 2024-01-03, the feature already contains the answer.
The fix is to shift first, then roll. After shift(1), each row holds the previous row's value. The rolling window then sees only values from earlier dates.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
out = pd.DataFrame({
"sales": s,
"leaky": s.rolling(window=2).mean(),
"safe": s.shift(1).rolling(window=2).mean(),
})
print(out) sales leaky safe
2024-01-01 10 NaN NaN
2024-01-02 12 11.0 NaN
2024-01-03 15 13.5 11.0
2024-01-04 11 13.0 13.5On 2024-01-03, leaky is (12 + 15) / 2, which includes the day's own 15. safe is (10 + 12) / 2, which uses only the two previous days.
Shift then roll, or roll then shift
For statistics like the mean, s.shift(1).rolling(2).mean() and s.rolling(2).mean().shift(1) give the same result. Both move every window one step back in time. Pick one and use it consistently.
Shifting first has a practical advantage. You can see in the code that the raw values are lagged before anything is computed. That makes leakage easier to spot in review.
Choosing the window length and NaN handling
With window=2, the first two rows of safe are NaN. One NaN comes from the shift. The other comes from the window needing two values. In general, you lose window rows at the start of the series.
You can accept fewer observations at the start with min_periods:
early = s.shift(1).rolling(window=3, min_periods=1).mean()
print(early)2024-01-01 NaN
2024-01-02 10.0
2024-01-03 11.0
2024-01-04 12.333333
Freq: D, Name: sales, dtype: float64Early rows now use shorter windows, so their averages are noisier than later ones. Many models handle this better than a block of NaN, but you should know it happens.
Using closed="left" with time-based windows
If the index is a DatetimeIndex, you can give rolling() a time span such as "2D". Setting closed="left" excludes the current row from the window, which has the same effect as shifting.
by_time = s.rolling("2D", closed="left", min_periods=2).mean()
print(by_time)2024-01-01 NaN
2024-01-02 NaN
2024-01-03 11.0
2024-01-04 13.5
Freq: D, Name: sales, dtype: float64A time-based window counts calendar time, not rows. If a date is missing, the window still covers two days, so it may contain fewer values. Compare this with the row-based shift(1).rolling(2), which would silently reach back further. If your timestamps have gaps, either use a time-based window or call asfreq() first, as covered earlier.
Rolling features within groups
With several entities in one DataFrame, the shift and the window must both stay inside each group. Otherwise store B's first rows would use store A's last values.
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"date": pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-03"] * 2),
"sales": [10, 12, 15, 100, 90, 95],
})
df = df.sort_values(["store", "date"])
df["roll2_prev"] = df.groupby("store")["sales"].transform(
lambda x: x.shift(1).rolling(window=2).mean()
)
print(df) store date sales roll2_prev
0 A 2024-01-01 10 NaN
1 A 2024-01-02 12 NaN
2 A 2024-01-03 15 11.0
3 B 2024-01-01 100 NaN
4 B 2024-01-02 90 NaN
5 B 2024-01-03 95 95.0The function passed to transform() runs once per store, then the results are placed back in the original row order. Store B's first two rows are NaN, and its third row is (100 + 90) / 2 = 95.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `rolling()` without a shift | The current value is inside its own feature | Use `shift(1)` first, or `closed="left"` |
| Rolling on the whole DataFrame with groups | Windows cross group boundaries | Use `groupby().transform()` |
| Unsorted index or rows | "Previous" rows are not earlier in time | Sort by group and date first |
| Row-based window on a gappy index | Window spans more calendar time than intended | Use `asfreq()` or a time-based window |
Exercise
Using the Series s from this chapter, write one line that computes a leak-free 3-day rolling maximum of sales, so that the value on each date uses only the three days before it. What is the value on 2024-01-04?
Show answer
s.shift(1).rolling(window=3).max(). On 2024-01-04 the shifted series holds 15, 12 and 10 in the three-row window, so the result is 15. The first three rows (2024-01-01 to 2024-01-03) are NaN because the shift and the window length leave too few earlier values.