Sub topic 9
Building lag features for a forecasting model
This chapter assumes you know basic Python, how to build pandas Series and DataFrames, and how to use a DatetimeIndex with pd.date_range. It also assumes you have seen shift(), groupby().shift() and asfreq() from earlier chapters.
What a lag feature is
A forecasting model predicts a future value from information available now. Most models take a table of columns, not a time series. A lag feature turns the past into a column. The column sales_lag1 holds yesterday's sales on each row, so a model can use it to predict today's sales.
Building these features takes three steps:
- Put the data in a regular, sorted order.
- Shift within each group so that groups do not mix.
- Drop or handle the NaN rows that shifting creates.
Step 1: Sort and regularize
shift() moves values by row position. It is only correct as a lag when each row is one step in time and the rows are in time order. If a date is missing, shift(1) reaches back two days instead of one. If rows are unsorted, it reaches back to an unrelated row.
Sort first. If the index has gaps, call asfreq() so that each missing date appears as a NaN row.
Step 2: Lag within groups
Real data often holds many series in one table, such as one per store. Shifting the whole column would give store B the last value of store A. Group first, then shift.
import pandas as pd
df = pd.DataFrame({
"store": ["A"] * 5 + ["B"] * 5,
"date": list(pd.date_range("2024-01-01", periods=5, freq="D")) * 2,
"sales": [10, 12, 15, 11, 14, 100, 90, 95, 99, 102],
})
df = df.sort_values(["store", "date"])
g = df.groupby("store")["sales"]
df["lag1"] = g.shift(1)
df["lag2"] = g.shift(2)
print(df)The first row of each store has lag1 equal to NaN. The first two rows of each store have lag2 equal to NaN. Store B's first row does not receive store A's last value.
Step 3: Add change features and handle NaN
A lag is often more useful as a difference from the current value, so you can add that as a feature too. Here lag1 is yesterday's sales.
df["change_lag1"] = g.shift(1) - g.shift(2)
df["roll2_prev"] = g.transform(lambda x: x.shift(1).rolling(2).mean())
features = df.dropna()
print(features)change_lag1 is the change between the two previous days. It is not the change up to today, because today's value is what you want to predict. roll2_prev is a shifted rolling mean. The shift happens before the rolling window, so the window covers only earlier days.
dropna() removes the rows where any lag is undefined. This is the simplest option and it is usually right when you have plenty of history. If you cannot afford to lose rows, some models accept NaN directly, such as gradient boosting libraries. Filling with fill_value=0 is risky, because a zero looks like a real observation.
Step 4: Split by time
Once the features exist, split the table by date. Train on earlier dates and test on later ones.
cutoff = pd.Timestamp("2024-01-04")
train = features[features["date"] < cutoff]
test = features[features["date"] >= cutoff]
X_cols = ["lag1", "lag2", "change_lag1", "roll2_prev"]
print(train[X_cols].shape, test[X_cols].shape)A random split would put later rows in the training set. Because the lag columns copy values across rows, that mixes the future into training. A date cutoff avoids this.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Shifting without sorting | Lags come from unrelated rows | `sort_values` by group and date |
| Shifting a stacked table without `groupby` | Groups receive each other's values | `groupby(...).shift()` |
| Gaps in the dates | `shift(1)` skips a day | `asfreq()` per series first |
| Using `shift(-1)` as a feature | The feature contains future data | Use positive periods only |
| Filling NaN with 0 | The model sees false zeros | `dropna()` or keep NaN |
Exercise
A table holds daily sales for 3 stores, sorted by store and date. You build lag7 with df["sales"].shift(7) and no groupby. How many rows per store besides the first store's first 7 rows get a wrong lag, and how do you fix it?
Show answer
The first 7 rows of the second store and the first 7 of the third store each receive values from the end of the previous store, so 14 rows are wrong, and the first store's 7 rows are correctly NaN. Fix it with df.groupby("store")["sales"].shift(7), which leaves the first 7 rows of every store as NaN.
Exercise
Why is x.shift(1).rolling(2).mean() safer as a feature than x.rolling(2).mean() when you predict the value at time t?
Show answer
The unshifted rolling mean at time t includes the value at time t, which is the quantity you are trying to predict. Shifting first means the window ends at time t-1, so the feature uses only past data.