Sub topic 8
Lagging within groups
This chapter assumes you know how shift() works on a single Series, including the NaN it creates at the edge. You should also be comfortable with groupby() on a DataFrame.
The problem with a plain shift
Real data often holds several time series in one table, such as one series per store, sensor, or customer. A plain shift(1) knows nothing about those boundaries. It moves every value down one row, so the first row of one group receives the last value of the group above it.
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"])
df["naive_lag1"] = df["sales"].shift(1)
print(df) store date sales naive_lag1
0 A 2024-01-01 10 NaN
1 A 2024-01-02 12 10.0
2 A 2024-01-03 15 12.0
3 B 2024-01-01 100 15.0
4 B 2024-01-02 90 100.0
5 B 2024-01-03 95 90.0Store B's first lag is 15, which is store A's last sale. No error is raised, so this bug is easy to miss.
Shifting inside each group
Call shift() on a grouped column. pandas then shifts each group separately, and each group's first row becomes NaN.
df["sales_lag1"] = df.groupby("store")["sales"].shift(1)
print(df[["store", "date", "sales", "sales_lag1"]]) store date sales sales_lag1
0 A 2024-01-01 10 NaN
1 A 2024-01-02 12 10.0
2 A 2024-01-03 15 12.0
3 B 2024-01-01 100 NaN
4 B 2024-01-02 90 100.0
5 B 2024-01-03 95 90.0The result has the same index as the original DataFrame. That is why you can assign it straight to a new column, and rows stay aligned even if the groups are interleaved.
flowchart TDSort first
shift() is positional. It moves values by row order within each group and does not look at dates. If a group's rows are out of date order, the lag is wrong even with groupby. Sort by the group key and the date before you shift, as the example does with sort_values(["store", "date"]).
Other options that work per group
The options you already know carry over unchanged:
fill_valuereplaces theNaNat the start of each group:groupby("store")["sales"].shift(1, fill_value=0).- A negative
periodscreates a lead inside each group. groupby("store")["sales"].diff()gives the change from the previous row within each store.groupby("store")["sales"].pct_change()gives the relative change within each store.
You can also create several lags in one pass:
grouped = df.groupby("store")["sales"]
for k in (1, 2):
df[f"sales_lag{k}"] = grouped.shift(k)
print(df.columns.tolist())Reusing the grouped object avoids repeating the group lookup. The loop adds sales_lag1 and sales_lag2.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| First row of a group has a value from another group | Plain `shift()` was used | Use `groupby(key)[col].shift()` |
| Lags look shifted by the wrong amount | Rows not sorted by date | Sort by key and date first |
| A lag skips a day | A date is missing inside a group | Regularize each group's dates, then shift |
| `KeyError` on the group column | Group key is the index, not a column | Use `groupby(level=...)` or `reset_index()` |
Missing dates are the subtle case. Row-based shifting counts rows, not days. If store A has no row for January 3, then shift(1) on January 4 returns January 2's value. You can regularize each group with asfreq() after setting the date as the index, or you can use shift(1, freq="D") and join the result back on store and date. Both approaches make "one step" mean one calendar day.
Summary
- Plain
shift()leaks values across group boundaries. groupby(key)[col].shift(n)shifts each group on its own and leavesNaNat each group's start.- Sort by key and date first, because shifting follows row position.
Exercise
A DataFrame readings has columns sensor, time, and temp, and is already sorted by sensor and time. Write one line that adds a column temp_prev holding each sensor's previous temperature, so the first reading of every sensor is 0 instead of NaN.
Show answer
readings["tempprev"] = readings.groupby("sensor")["temp"].shift(1, fillvalue=0)