Sub topic 8
Lagging within groups
Real datasets rarely hold one series. A retail table has one sales history per store, a sensor log has one per device, and a price table has one per ticker. A plain shift() treats the whole column as one series, so it mixes the groups. This chapter shows how to lag each group separately with groupby().shift(), and what to check before you trust the result.
This chapter assumes you know basic Python and how to create and index pandas Series and DataFrames. It also assumes you know pd.date_range, and that you have met shift(periods), fill_value, diff() and pct_change() in the earlier chapters.
Why a plain shift() fails on grouped data
shift() moves values by row position. It has no idea that rows 0 to 2 belong to store A and rows 3 to 5 belong to store B. At the boundary between groups, it hands the last value of one group to the first row of the next.
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"]).reset_index(drop=True)
df["wrong_lag1"] = df["sales"].shift(1)
df["sales_lag1"] = df.groupby("store")["sales"].shift(1)
print(df) store date sales wrong_lag1 sales_lag1
0 A 2024-01-01 10 NaN NaN
1 A 2024-01-02 12 10.0 10.0
2 A 2024-01-03 15 12.0 12.0
3 B 2024-01-01 100 15.0 NaN
4 B 2024-01-02 90 100.0 100.0
5 B 2024-01-03 95 90.0 90.0Row 3 is the problem. The plain shift gives store B's first day a "previous value" of 15, which is store A's last sales figure. The grouped version gives NaN, which is correct: store B has no earlier observation in this data.
This kind of error produces no warning and no exception. The column looks plausible, and a model trained on it will quietly learn from wrong inputs.
How groupby().shift() works
df.groupby("store")["sales"].shift(1) splits the column into one piece per store and shifts each piece independently. Then it puts the results back in the original row order.
Two properties matter in practice:
- The result has the same index as the input. You can assign it straight to a new column, and no alignment surprises occur.
- The first
periodsrows of every group becomeNaN, exactly as in a single-series shift. With 100 stores andshift(1), you get 100NaNvalues, one per store.
Sort before you shift
shift() follows row order, not date order. If the rows inside a group are not sorted by time, the lag is not a time lag. The grouped version has the same weakness as the plain one.
import pandas as pd
unsorted = pd.DataFrame({
"store": ["A", "A", "A"],
"date": pd.to_datetime(["2024-01-03", "2024-01-01", "2024-01-02"]),
"sales": [15, 10, 12],
})
unsorted["lag_wrong"] = unsorted.groupby("store")["sales"].shift(1)
fixed = unsorted.sort_values(["store", "date"]).copy()
fixed["lag_ok"] = fixed.groupby("store")["sales"].shift(1)
print(unsorted)
print(fixed)In unsorted, the lag for January 1 is 15, which is the value from January 3. That is a value from the future. In fixed, the lags are NaN, 10 and 12, which are the correct previous-day values.
If your data has a DatetimeIndex and no separate date column, use df.sort_index() for a single series, or df.sort_values("store").sort_index(kind="stable") when you need a stable ordering inside groups. A simpler option is to move the date into a column and sort on both keys, as above.
Several lags, leads and changes
Create the grouped object once and reuse it. Each call computes its own shift, and the grouped object is cheap to keep around.
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],
}).sort_values(["store", "date"])
g = df.groupby("store")["sales"]
df["lag1"] = g.shift(1)
df["lag2"] = g.shift(2)
df["lead1"] = g.shift(-1)
df["change"] = g.diff()
df["pct"] = g.pct_change()
print(df)For store A, lag2 is NaN, NaN, 10, lead1 is 12, 15, NaN, and change is NaN, 2, 3. Store B starts again from NaN in every column. diff() and pct_change() on a grouped object do the same work as s - s.shift(1) and s / s.shift(1) - 1, restricted to each group.
A negative period gives a lead, and the NaN appears at the end of each group instead of the start. Leads are useful for building targets ("sales tomorrow"). Using them as input features is a leakage risk, which a later chapter covers.
To avoid copy-pasting, wrap the pattern in a helper:
import pandas as pd
def add_lags(frame, group_col, value_col, lags):
out = frame.copy()
grouped = out.groupby(group_col)[value_col]
for k in lags:
out[f"{value_col}_lag{k}"] = grouped.shift(k)
return out
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],
}).sort_values(["store", "date"])
print(add_lags(df, "store", "sales", [1, 2]))Filling the NaN values per group
fill_value works with groupby().shift() in the same way as on a Series. Each group's first row receives the fill value instead of NaN.
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"sales": [10, 12, 100, 90],
})
df["lag1_zero"] = df.groupby("store")["sales"].shift(1, fill_value=0)
print(df)Be careful with the choice of value. A zero lag says "the store sold nothing yesterday", which is false for a store that simply has no earlier record. For models, it is often better to leave NaN and let the model or an imputer deal with it, or to drop the early rows. Use fill_value when zero or another constant truly means "nothing before this point".
Shifting several columns at once
Select a list of columns and groupby().shift() returns a DataFrame with the same columns. You can rename them and join them back.
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],
"visits": [5, 6, 7, 50, 45, 48],
}).sort_values(["store", "date"])
lagged = (
df.groupby("store")[["sales", "visits"]]
.shift(1)
.add_suffix("_lag1")
)
df = df.join(lagged)
print(df)join lines the new columns up by index, which works because the grouped shift keeps the original index. This only holds if the index has no duplicate labels. If you concatenated tables, call reset_index(drop=True) first.
Gaps inside groups
Shifting by one row means "one observation back". It means "one day back" only if every group has a row for every day. When a store skips a date, the lag silently spans two days.
Fix this by regularizing each group before shifting. Setting the date as the index lets you resample per group and fill the missing dates with NaN.
import pandas as pd
gappy = pd.DataFrame({
"store": ["A", "A", "B", "B", "B"],
"date": pd.to_datetime(
["2024-01-01", "2024-01-03", "2024-01-01", "2024-01-02", "2024-01-03"]
),
"sales": [10, 15, 100, 90, 95],
})
daily = gappy.set_index("date").groupby("store")["sales"].resample("D").asfreq()
lagged = daily.groupby(level="store").shift(1)
print(pd.DataFrame({"sales": daily, "lag1": lagged}))Store A now has a row for January 2 with sales of NaN. Its lag for January 3 is therefore NaN (the true value for January 2 is unknown), and not 10. The lag for January 2 is 10, which is correct. Store B is unchanged, because it had no gaps.
Note that resample here only fills dates between each group's own first and last date. Store A does not get rows before January 1 or after January 3. If you need every store aligned to one shared calendar, reindex to a full MultiIndex built from every store and every date instead.
Choosing an approach
| Situation | Use | Watch for |
|---|---|---|
| One series, regular index | `s.shift(k)` | Nothing special |
| Several groups, regular rows, sorted | `df.groupby(key)[col].shift(k)` | Sort by key and date first |
| Several groups, some dates missing | Resample each group to a regular frequency, then group and shift | New rows carry `NaN`, so lags can be `NaN` too |
| Row order unreliable | `sort_values([key, "date"])` before anything else | Stale columns computed before the sort |
Common errors
- Forgetting the groupby. The plain
shift()runs without error and leaks values across groups. Check the first row of every group after you build a lag column. - Sorting only by date. Sorting by date alone interleaves the groups. Sort by group key first, then date. The grouped shift handles interleaving correctly as long as each group's rows are in time order, but sorting by both keys is easier to inspect.
- Assuming shift(1) means one day. It means one row. Verify with
df.groupby("store")["date"].diff().value_counts(). Any value other than your expected step, such as one day, points to gaps or duplicates. - Duplicate timestamps within a group. Two rows for the same store and date make the lag ambiguous. Aggregate them first, for example with
groupby(["store", "date"])["sales"].sum(). - Filling with zero by default. It hides the fact that the history is missing.
- Computing a lag, then sorting differently. The lag belongs to the row order at the time of the shift. Re-sorting the whole DataFrame afterwards is safe because the lag column moves with its row, but recomputing it from a different order is not.
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],
}).sort_values(["store", "date"])
df["lag1"] = df.groupby("store")["sales"].shift(1)
first_rows = df.groupby("store")["lag1"].first()
assert first_rows.isna().all()
expected = df.groupby("store")["sales"].shift(1)
assert df["lag1"].equals(expected)
print("lag checks passed")Exercises
Exercise
A table has columns store, date and sales, sorted by date only. Rows for store A and store B alternate. You run df.groupby("store")["sales"].shift(1). Is the result a correct one-day lag? Explain.
Show answer
Yes only if every store has exactly one row per day, because the shift then moves each group's values by one row and the rows of each store are in date order. The interleaving does not matter for the grouped shift, since each group is shifted separately. If a store skips a day, shift(1) spans two days for that store, so you should regularize each group first. Sorting by store and date makes the table easier to inspect.
Exercise
Why does df["sales"].shift(1) put store A's last value on store B's first row, and what is the one-line fix?
Show answer
shift() works on row position and ignores the store column, so the last row of A is followed by the first row of B. The fix is df.groupby("store")["sales"].shift(1), which shifts inside each store and leaves NaN on each store's first row.
Exercise
Store A has sales on January 1 and January 3 only. After you resample it to daily frequency with asfreq, what is the one-day lag on January 3, and why is that better than shifting the original two rows?
Show answer
The lag on January 3 is NaN, because January 2 is a new row with no sales value. Shifting the original two rows would give 10 (the January 1 value) as the "previous day" value for January 3, which is really two days old.