Sub topic 9
Avoiding look-ahead leakage with shift
This chapter assumes you can build a rolling mean with rolling(window), know that the first rows of a result are NaN until the window fills, and can read a DataFrame with a default integer index. You should also know what a prediction target is in a basic machine learning setup.
What look-ahead leakage is
Look-ahead leakage happens when a feature for a row uses information that would not have been available at the time you needed to make the prediction. The model then looks accurate in testing, but it fails in production because the extra information is not there.
Rolling windows cause leakage easily. By default, rolling(3) ends on the current row, so the window includes the current value. If the current value is also what you want to predict, the feature contains the answer.
Suppose you want to predict today's sales from past sales. A feature built with rolling(3).mean() on row t averages the sales on days t-2, t-1 and t. Day t is the target, so part of the feature is the target itself.
Shifting the rolling result
The fix is to move the rolling result down one row with shift(1). After the shift, row t holds the window that ended at row t-1. The window now uses only earlier rows.
import pandas as pd
df = pd.DataFrame({"sales": [10, 20, 30, 40, 50, 60]})
df["feature"] = df["sales"].rolling(3).mean().shift(1)
print(df)The output is:
| row | sales | feature |
|---|---|---|
| 0 | 10 | NaN |
| 1 | 20 | NaN |
| 2 | 30 | NaN |
| 3 | 40 | 20.0 |
| 4 | 50 | 30.0 |
| 5 | 60 | 40.0 |
Row 3 has a feature of 20.0, which is the mean of 10, 20 and 30. The value 40 on that row is not part of it. The shift adds one more NaN at the top, so the first three rows have no feature.
Order matters
You can also shift the input before rolling, and for a plain rolling mean the result is the same. Both of these give identical values:
import pandas as pd
s = pd.Series([10, 20, 30, 40, 50, 60])
a = s.rolling(3).mean().shift(1)
b = s.shift(1).rolling(3).mean()
print(a.equals(b))This prints True. Pick one style and use it consistently, so a reader can tell at a glance that the feature is lagged.
Alternatives to shift
A second option is closed="left" on a time-based window. It excludes the right edge of the window, which is the current row, so no shift is needed. This works with offset windows such as "3D" on a DatetimeIndex.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
s = pd.Series([10, 20, 30, 40, 50, 60], index=idx)
print(s.rolling("3D", closed="left").mean())Each row now averages the days before it, up to three days back. The first row has no earlier data, so it is NaN.
Common mistakes
- Shifting the wrong direction.
shift(-1)moves values up, so each row sees the next row's window. That creates leakage instead of removing it. - Using
center=Truefor features. A centered window includes rows after the current one. It is fine for smoothing a chart, but not for a feature used to predict. - Using
expanding()without a shift. An expanding mean at rowtincludes rowt, so it has the same problem asrolling. - Shifting across groups. If you compute features per group, shift inside each group. A plain
shift(1)on a stacked frame lets the last row of group A leak into the first row of group B.
Shifting within groups
Apply the shift inside groupby so each store gets its own lag:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 30],
})
df["feature"] = df.groupby("store")["sales"].transform(
lambda s: s.rolling(2).mean().shift(1)
)
print(df)Store B's first two rows are NaN, so no value from store A appears in store B's features.
Exercise
A DataFrame has a daily "demand" column. You write df["f"] = df["demand"].rolling(7).mean() and use f to predict demand on the same row. Why is this leaky, and how do you fix it in one change?
Show answer
The 7-row window ends on the current row, so f includes the demand value you are trying to predict. Add shift(1): df["f"] = df["demand"].rolling(7).mean().shift(1). Now row t uses rows t-7 through t-1.
Exercise
What does s.rolling(3, center=True).mean() do that makes it unsuitable as a prediction feature?
Show answer
A centered window covers one row before, the current row, and one row after. It uses a future value, so it leaks information that would not exist at prediction time.