Sub topic 3
Lagging Within Groups
Assume you know basic pandas, DataFrame indexing, and DatetimeIndex. A lag is a previous value aligned with the current row. When data contains several entities, such as stores or machines, calculate each lag separately within each entity.
Lagging Within Groups
Sort by group and time before shifting. Then use groupby().shift():
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",
"2024-01-01", "2024-01-02", "2024-01-03",
]),
"sales": [10, 12, 15, 100, 90, 95],
}).sort_values(["store", "date"])
df["sales_lag1"] = df.groupby("store")["sales"].shift(1)
print(df)The first row for each store has NaN, because that store has no earlier observation. Store B does not receive store A's final value.
Building Lag Features for a Forecasting Model
A feature is an input column used by a model. Lag features let a forecasting model use historical values:
df["sales_lag2"] = df.groupby("store")["sales"].shift(2)
df["sales_change"] = df["sales"] - df["sales_lag1"]Rows without enough history contain NaN. Usually, remove those rows from the training data or handle them according to the model's requirements.
Avoiding Lookahead Leakage
Lookahead leakage occurs when a training feature uses information that would be unknown at prediction time. Use positive periods for past values:
shift(1)uses the previous row.shift(2)uses the value from two rows earlier.shift(-1)uses the next row and can leak future information.
Create lags before splitting or fitting the model, then ensure every feature uses only data available at its prediction timestamp.
Shifted Rolling Statistics
A rolling statistic summarizes a moving window. Shift before rolling when the current value must not affect its own feature:
df["prior_2_day_mean"] = (
df.groupby("store")["sales"]
.shift(1)
.rolling(2)
.mean()
)For complex grouped rolling operations, check the resulting index and align the output back to df carefully. The key order is: sort by group and time, shift to exclude the current row, then calculate the rolling statistic.
Exercise
Why does each store have NaN in its first sales_lag1 row?
Show answer
That row has no earlier sales value within the same store.