Sub topic 11
Shifted Rolling Statistics
A rolling statistic summarizes the last few values of a series, such as a 7-day average of sales. It is a common feature in forecasting models. If you compute it the obvious way, the current row's own value ends up inside the feature. This chapter shows how shift() fixes that, how to choose the window parameters, and how to apply the pattern within groups, across gaps, and at longer forecast horizons.
It assumes you know shift(), groupby().shift(), asfreq(), and the idea of lookahead leakage from the earlier chapters.
Why a plain rolling window leaks
rolling(window=3).mean() is a trailing window, but it includes the current row. At date t it averages the values at t-2, t-1, and t. If the value at t is what you want to predict, the feature already contains part of the answer.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11, 14, 18, 16],
index=pd.date_range("2024-01-01", periods=7, freq="D"),
name="sales",
)
features = pd.DataFrame({
"sales": s,
"roll3_leaky": s.rolling(window=3).mean(),
"roll3_safe": s.shift(1).rolling(window=3).mean(),
})
print(features.round(2)) sales roll3_leaky roll3_safe
2024-01-01 10 NaN NaN
2024-01-02 12 NaN NaN
2024-01-03 15 12.33 NaN
2024-01-04 11 12.67 12.33
2024-01-05 14 13.33 12.67
2024-01-06 18 14.33 13.33
2024-01-07 16 16.00 14.33On 2024-01-03, roll3_leaky is 12.33, the average of 10, 12, and 15. The 15 is the value you would be trying to predict. roll3_safe on 2024-01-04 is also 12.33, but it is built from 10, 12, and 15, all of which happened before that date.
Shift first or roll first
For fixed-size windows on a regular index, the order does not change the result. Shifting the series and then rolling gives the same numbers as rolling and then shifting the result.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11, 14, 18, 16],
index=pd.date_range("2024-01-01", periods=7, freq="D"),
name="sales",
)
a = s.shift(1).rolling(3).mean()
b = s.rolling(3).mean().shift(1)
pd.testing.assert_series_equal(a, b)
print("identical")Use assert_series_equal instead of == because rolling means can differ in the last floating-point digit.
Prefer writing shift first. A reader sees the shift before the statistic, so the code is easier to audit for leakage. It also works with statistics you build yourself, such as rolling(...).apply(func).
The extra NaN and min_periods
shift(1) adds one NaN at the start. A fixed window requires min_periods non-NaN values, and min_periods defaults to the window size. A 3-row window on a shifted series therefore produces three leading NaN rows. The unshifted version produces two.
You can trade completeness for noise by lowering min_periods:
min_periods=window(default): every feature uses a full window. The first rows are NaN.min_periods=1: the first usable row is built from a single value. The feature is noisy early on, and a standard deviation needs at least 2.- Dropping the leading NaN rows before training is often better than filling them. Rows built from one observation behave differently from rows built from a full window, and the model has no way to tell them apart.
Other statistics
The same shift-then-summarize pattern works for any window method, including expanding and exponentially weighted ones.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11, 14, 18, 16],
index=pd.date_range("2024-01-01", periods=7, freq="D"),
name="sales",
)
past = s.shift(1)
stats = pd.DataFrame({
"mean3": past.rolling(3, min_periods=1).mean(),
"std3": past.rolling(3, min_periods=2).std(),
"max3": past.rolling(3, min_periods=1).max(),
"ewm_mean": past.ewm(span=3).mean(),
"expanding_mean": past.expanding().mean(),
})
print(stats.round(2))Binding past = s.shift(1) once and building every feature from past is a useful habit. A feature that calls s directly instead of past is easy to spot in review.
Shifting by the forecast horizon
Shifting by 1 assumes you forecast one step ahead, so the previous row is the newest value you will have. If you forecast h steps ahead, the newest value available when predicting row t is the one at t-h. The shift must be h.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11, 14, 18, 16],
index=pd.date_range("2024-01-01", periods=7, freq="D"),
name="sales",
)
h = 2
feature_h2 = s.shift(h).rolling(window=3).mean()
print(feature_h2.round(2))With h = 2, the feature on 2024-01-05 is the mean of 10, 12, and 15, which are the values from 2024-01-01 to 2024-01-03. A shift(1) feature would use 2024-01-04, a day your model would not have seen yet in a two-day-ahead forecast.
Rolling statistics within groups
With several entities in one DataFrame, a global shift(1) followed by rolling mixes entities at group boundaries. Do both steps inside each group. groupby().rolling() returns a MultiIndex that you then have to realign. A transform with a small function keeps the original index and is easier.
import pandas as pd
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["past_mean2"] = df.groupby("store")["sales"].transform(
lambda x: x.shift(1).rolling(window=2, min_periods=1).mean()
)
print(df) store date sales past_mean2
0 A 2024-01-01 10 NaN
1 A 2024-01-02 12 10.0
2 A 2024-01-03 15 11.0
3 B 2024-01-01 100 NaN
4 B 2024-01-02 90 100.0
5 B 2024-01-03 95 95.0Store B's first row is NaN, as it should be. If you had shifted and rolled the whole sales column without grouping, B's first row would be 13.5, which is the mean of A's last two values.
Sort by group and date before you start. Both shift and rolling work on row order, not on dates.
Gaps in the index
On a series with missing dates, shift(1) means "previous row", which may be several days back. A rolling window of 2 rows then spans a longer period than you intended. There are two fixes.
- Regularize with
asfreq()so every date exists, then shift and roll. The gap becomes NaN, which rolling skips whenmin_periodsallows. - Use a time-based window with
closed="left", which excludes the current timestamp and works directly on irregular data.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
irregular = s.drop(pd.Timestamp("2024-01-03"))
by_rows = irregular.shift(1).rolling(2, min_periods=1).mean()
by_time = irregular.rolling("2D", closed="left", min_periods=1).mean()
regular = irregular.asfreq("D")
by_asfreq = regular.shift(1).rolling(2, min_periods=1).mean()
print(pd.DataFrame({
"by_rows": by_rows,
"by_time": by_time,
}))
print(by_asfreq) by_rows by_time
2024-01-01 NaN NaN
2024-01-02 10.0 10.0
2024-01-04 11.0 12.0
2024-01-01 NaN
2024-01-02 10.0
2024-01-03 11.0
2024-01-04 12.0
Freq: D, Name: sales, dtype: float64On 2024-01-04, by_rows averages 10 and 12, so it reaches back to 2024-01-01 for a "2-day" feature. by_time sees only the values in the two days before the timestamp, which is just the 12 from 2024-01-02. The asfreq version agrees with by_time on that date (12.0) and also adds a row for the missing 2024-01-03.
A few details about time-based windows:
- The index must be a monotonic DatetimeIndex.
min_periodsdefaults to 1 for time-based windows, not to the window size. Set it explicitly if you want a full window.closed="left"gives the interval[t - window, t). It includes the point exactlywindowbeforetand excludest. With the defaultclosed="right", the current row is in the window, which brings the leak back.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| `s.rolling(3).mean()` used as a feature for `s` | The target is inside its own feature | Use `s.shift(1).rolling(3).mean()` |
| Shifting by 1 for a multi-step forecast | Uses values not yet available at prediction time | Shift by the horizon `h` |
| Global shift on stacked groups | One group's tail leaks into the next group's head | `groupby(...).transform(lambda x: ...)` |
| Row-based window on a series with gaps | The window covers more calendar time than intended | `asfreq()` first, or a time-based window with `closed="left"` |
| Unsorted data | Shift and rolling follow row order, not dates | `sort_values` by group and date first |
| Time-based window with the default `closed` | The current row is included | Pass `closed="left"` |
Exercises
Exercise
Given s = pd.Series([4, 6, 8, 10, 12], index=pd.date_range("2024-02-01", periods=5, freq="D")), write one expression for a 2-row rolling mean that uses only values before each date. What are its five values?
Show answer
s.shift(1).rolling(2).mean(). The values are NaN, NaN, 5.0, 7.0, 9.0. The shifted series is NaN, 4, 6, 8, 10. A 2-row window needs two non-NaN values, so the first valid window ends on the third date and averages 4 and 6.
Exercise
You forecast daily sales 7 days ahead and want a 3-day rolling mean feature. Which expression is correct: s.shift(1).rolling(3).mean(), s.rolling(3).mean().shift(7), or s.rolling(3).mean()? Explain why the other two fail.
Show answer
s.rolling(3).mean().shift(7) is correct. Shifting by the horizon of 7 ensures the newest value in the feature is from 7 days before the target date. The first option only leaves a 1-day gap, so it uses days that will not be available at forecast time. The third includes the target day itself and leaks.
Exercise
A DataFrame holds stacked rows for stores A and B, sorted by store and date. df["sales"].shift(1).rolling(3, min_periods=1).mean() gives a non-NaN value on store B's first row. Why is that wrong, and how do you fix it?
Show answer
The global shift moves store A's last value onto store B's first row, and the rolling window then averages A's trailing values into B's feature. Compute both steps inside each group: df.groupby("store")["sales"].transform(lambda x: x.shift(1).rolling(3, min_periods=1).mean()). B's first row is then NaN.
Exercise
What does rolling("3D", closed="left", min_periods=3) do differently from shift(1).rolling(3, min_periods=3) on a daily series that is missing some dates?
Show answer
The time-based version looks at the 3 calendar days before each timestamp, and returns NaN when fewer than 3 observations fall in that interval. The row-based version always takes the previous 3 rows, which may reach back more than 3 days when dates are missing.