TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Lag, Rolling and Group Aggregation Features

Lag, Rolling and Group Aggregation Features

Many rows are not independent facts but moments in a history. Today's sales depend on yesterday's and on the same weekday last week; a card payment is suspicious if it is ten times what this customer usually spends. A single row does not contain that history, so we copy it in as features: lags (the value some steps back), rolling windows (a statistic over the last few steps) and group aggregations (a statistic over all rows of the same customer, device or shop). They are among the most useful features in practice and also the easiest way to leak the answer into the input. The time-series side is continued in Preparing Time-Series Data; what a time series is was covered in Time Series Data.

The one rule: only the past

Every one of these features must be computable at the moment of prediction. For a forecast of day t, you know days up to t-1 (or up to the forecast origin), never day t itself. In pandas this means: sort by time, group by the entity, then shift before any rolling statistic.

days t-7 t-6 ... t-4 t-3 t-2 t-1 t (target) rolling mean of 3 lag 7 ... lag 1 features use only days before t: shift first, then roll

Lags and rolling windows in pandas

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
days = pd.date_range("2026-01-01", periods=10, freq="D")
sales = pd.DataFrame({"day": days, "units": rng.poisson(20, 10)})

past = sales["units"].shift(1)                      # yesterday is the newest value we may use
sales["lag_1"] = past
sales["lag_7"] = sales["units"].shift(7)
sales["roll_mean_3"] = past.rolling(3).mean()
sales["roll_max_3"] = past.rolling(3).max()
sales["leaky_mean_3"] = sales["units"].rolling(3).mean()   # WRONG: includes today's target
print(sales.round(2).to_string(index=False))
       day  units  lag_1  lag_7  roll_mean_3  roll_max_3  leaky_mean_3
2026-01-01     22    NaN    NaN          NaN         NaN           NaN
2026-01-02      9   22.0    NaN          NaN         NaN           NaN
2026-01-03     21    9.0    NaN          NaN         NaN         17.33
2026-01-04     25   21.0    NaN        17.33        22.0         18.33
2026-01-05     26   25.0    NaN        18.33        25.0         24.00
2026-01-06     23   26.0    NaN        24.00        26.0         24.67
2026-01-07     26   23.0    NaN        24.67        26.0         25.00
2026-01-08     17   26.0   22.0        25.00        26.0         22.00
2026-01-09     22   17.0    9.0        22.00        26.0         21.67
2026-01-10     21   22.0   21.0        21.67        26.0         20.00

The first rows have NaN where the history is too short; drop them or impute with a flag (a new store has no lag-7). The column leaky_mean_3 is the classic mistake: on 2026-01-03 it averages days 1 to 3, including the very value we are trying to predict.

How much a leak inflates the score

We forecast daily units from the lag and rolling features, with a chronological split (first 300 days for training, last 100 for testing), once with the honest 3-day rolling mean and once with the leaky one:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error

rng = np.random.default_rng(1)
n = 400
t = np.arange(n)
level = 50 + 10 * np.sin(2 * np.pi * t / 7) + np.cumsum(rng.normal(0, 1, n))
units = level + rng.normal(0, 4, n)
df = pd.DataFrame({"units": units})
past = df["units"].shift(1)
df["lag_1"] = past
df["lag_2"] = df["units"].shift(2)
df["lag_7"] = df["units"].shift(7)
df["roll_3"] = past.rolling(3).mean()
df["leaky_roll_3"] = df["units"].rolling(3).mean()
df = df.dropna()

train, test = df.iloc[:300], df.iloc[300:]
for feats in (["lag_1", "lag_2", "lag_7", "roll_3"], ["lag_1", "lag_2", "lag_7", "leaky_roll_3"]):
    model = Ridge().fit(train[feats], train["units"])
    mae = mean_absolute_error(test["units"], model.predict(test[feats]))
    print(f"{feats[-1]:13s} test MAE = {mae:.2f}")
print("naive forecast (yesterday):", round(mean_absolute_error(test["units"], test["lag_1"]), 2))
roll_3        test MAE = 4.97
leaky_roll_3  test MAE = 0.01
naive forecast (yesterday): 7.42

The leaky model is almost perfect (MAE 0.01 against 4.97), and not because it learned anything about demand: with lag_1, lag_2 and a 3-day mean that includes today, today is simply 3 * leaky_roll_3 - lag_1 - lag_2, and a linear model finds that identity. Such a feature can never be built in production, because on the morning of a forecast today's units are unknown. Real leaks are rarely this exact, but they work the same way. The honest model is the one to compare with the naive "same as yesterday" baseline (7.42).

Group aggregations: statistics per entity

"How unusual is this payment for this customer?" needs the customer's typical amount. Computing groupby("customer").mean() on the whole dataset and joining it back leaks twice: test rows contribute to the statistic, and every row's own amount is in its own average. The safe version learns the per-group statistics on the training rows only, like any other fitted step, and falls back to the global value for groups never seen in training. A small scikit-learn transformer does exactly that, so it can sit in a pipeline and be refitted inside every cross-validation fold:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin

class GroupStats(BaseEstimator, TransformerMixin):
    """Adds the mean and count of `value` per `key`, learned from the training rows only."""
    def __init__(self, key, value):
        self.key, self.value = key, value
    def fit(self, X, y=None):
        g = X.groupby(self.key)[self.value]
        self.mean_, self.count_ = g.mean(), g.count()
        self.global_mean_ = X[self.value].mean()
        return self
    def transform(self, X):
        out = X.copy()
        out[f"{self.key}_mean"] = X[self.key].map(self.mean_).fillna(self.global_mean_)
        out[f"{self.key}_count"] = X[self.key].map(self.count_).fillna(0).astype(int)
        out["ratio_to_mean"] = out[self.value] / out[f"{self.key}_mean"]
        return out

train = pd.DataFrame({"customer": ["ann", "ann", "ann", "bob", "bob", "cy"],
                      "amount": [12.0, 15.0, 9.0, 80.0, 95.0, 30.0]})
test = pd.DataFrame({"customer": ["ann", "bob", "dee"], "amount": [120.0, 85.0, 40.0]})

gs = GroupStats("customer", "amount").fit(train)
print(gs.transform(test).round(2).to_string(index=False))
customer  amount  customer_mean  customer_count  ratio_to_mean
     ann   120.0          12.00               3          10.00
     bob    85.0          87.50               2           0.97
     dee    40.0          40.17               0           1.00

Ann's 120 is 10 times her usual amount, a strong fraud signal; Bob's 85 is ordinary for him; Dee is new, so she gets the global mean and a count of 0, and the count tells the model how much to trust the mean. In a time-ordered problem you would go one step further and use an expanding statistic (only the customer's earlier rows: groupby(...).transform(lambda s: s.shift(1).expanding().mean())), so that even training rows never see their own future.

Pitfalls

  • Rolling without shift: the window includes the current target. Shift first, always.
  • Not sorting: lags on unsorted data point to random rows. Sort by entity and time, and check for gaps (a missing day makes shift(1) jump two days; reindex to a full calendar first).
  • Lags across entities: shift on a table of many shops must be done per shop (groupby("shop")["units"].shift(1)), or shop B's first row gets shop A's last value.
  • Group statistics on all data: fit them on training folds only; see also target encoding, the same idea applied to the label.
  • Forecast horizon: to predict 7 days ahead, the newest usable value is 7 days old, so the smallest valid lag is 7, not 1.

Practice

  1. You forecast tomorrow's electricity demand at 18:00 today, with data up to 17:00. Which of these are valid: demand at 17:00 today, the mean of the last 24 hours, tomorrow's weather forecast, tomorrow's actual temperature?
Answer

Valid: demand at 17:00 today, the mean of the last 24 hours up to 17:00, and tomorrow's weather forecast (it exists at 18:00 today). Invalid: tomorrow's actual temperature, which is only known tomorrow. Training on actual temperatures and serving with forecasts also creates a train/serve mismatch.

  1. Write the pandas expression for "number of earlier purchases by the same customer" in a table sorted by time.
Answer

df.groupby("customer").cumcount() counts the rows before the current one within each customer (0 for the first purchase), so it only uses the past.

Test yourself

What is wrong with df['units'].rolling(7).mean() as a feature for predicting units?

  1. Nothing
  2. The window includes the current row, the value being predicted
  3. Rolling means need scaling first
  4. It should be 30 days

A model forecasts sales 14 days ahead. What is the smallest lag it may use?

  1. 1
  2. 7
  3. 14
  4. 28

Per-customer average amounts are computed on the whole dataset and joined to every row. What is the problem?

  1. It is slow
  2. Test rows and each row's own amount contribute to the feature, so the evaluation is optimistic
  3. Averages cannot be features
  4. New customers get too much weight

A table holds daily sales for 50 shops stacked one after another. How should lag_1 be computed?

  1. df['sales'].shift(1)
  2. df.groupby('shop')['sales'].shift(1) after sorting by shop and date
  3. df['sales'].diff()
  4. df['sales'].rolling(1).mean()