Sub topic 8
Rolling windows within groups
This chapter shows how to run rolling and expanding statistics separately for each group, such as each store, sensor, or customer. It assumes you can use groupby, a DatetimeIndex, and rolling(window) with min_periods, as covered in earlier chapters.
Why a plain rolling call fails on grouped data
A rolling window moves over rows in order. It knows nothing about a store or customer column. If one DataFrame holds several groups stacked on top of each other, the window slides across the boundary and mixes values from different groups.
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 30],
})
print(df["sales"].rolling(2).mean())
# 0 NaN
# 1 1.5
# 2 2.5
# 3 6.5
# 4 15.0
# 5 25.0Row 3 is the first row of store B. Its value, 6.5, is the mean of 3 (store A) and 10 (store B). That number describes neither store. The first row of each group should be NaN, because it has no earlier row in its own group.
The fix is to split the data by group first, roll inside each group, and combine the results.
The groupby-then-rolling pattern
Call groupby, select the column, then call rolling and an aggregation:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 30],
})
result = df.groupby("store")["sales"].rolling(2).mean()
print(result)
# store
# A 0 NaN
# 1 1.5
# 2 2.5
# B 3 NaN
# 4 15.0
# 5 25.0
# Name: sales, dtype: float64Each store now starts with its own NaN, and no window crosses from A to B.
The result has a two-level index. The first level is the group key. The second level is the row label from the original DataFrame. Pandas builds this index because the output is ordered by group, not by the original row order.
Putting the result back on the original rows
To store the result as a new column, drop the group level so the index matches the original rows again:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "B", "A", "B", "A", "B"],
"sales": [1, 10, 2, 20, 3, 30],
})
df["avg2"] = (
df.groupby("store")["sales"]
.rolling(2)
.mean()
.reset_index(level=0, drop=True)
)
print(df)
# store sales avg2
# 0 A 1 NaN
# 1 B 10 NaN
# 2 A 2 1.5
# 3 B 20 15.0
# 4 A 3 2.5
# 5 B 30 25.0In this example the stores alternate. The grouped result is ordered A, A, A, B, B, B, with labels 0, 2, 4, 1, 3, 5. After reset_index(level=0, drop=True), the assignment aligns by label, not by position. That is why every value lands on the right row.
Alignment by label creates one requirement.
An alternative: transform
transform returns a result with the same index as the input, so no cleanup is needed:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "B", "A", "B", "A", "B"],
"sales": [1, 10, 2, 20, 3, 30],
})
df["avg2"] = df.groupby("store")["sales"].transform(
lambda s: s.rolling(2).mean()
)
print(df["avg2"].tolist())
# [nan, nan, 1.5, 15.0, 2.5, 25.0]The lambda receives one group's column as a Series, and the rolling call runs on that Series alone. The trade-off is speed. The function is called once per group in Python, which costs more than the built-in groupby().rolling() when there are many small groups. For typical datasets the difference is small, and the shorter code is easier to read.
| Approach | Index of the result | Cleanup needed | Best when |
|---|---|---|---|
| `groupby(...).rolling(...).agg()` | Group key plus original index | `reset_index(level=0, drop=True)` | You want the built-in path and the index is unique |
| `groupby(...).transform(lambda s: s.rolling(...)...)` | Same as the input | None | You want simple code or the index has duplicates |
Several group keys and several aggregations
When you group by more than one column, the result has one index level per key. Drop all of them:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "A", "B", "B", "B", "B"],
"product": ["x", "y", "x", "y", "x", "y", "x", "y"],
"sales": [1, 2, 3, 4, 5, 6, 7, 8],
})
df["total2"] = (
df.groupby(["store", "product"])["sales"]
.rolling(2)
.sum()
.reset_index(level=[0, 1], drop=True)
)
print(df["total2"].tolist())
# [nan, nan, 4.0, 6.0, nan, nan, 12.0, 14.0]The rule is to drop as many levels as there are group keys. The original row label is always the last level and is the one you keep.
You can also pass a list to agg after rolling. The result is a DataFrame with one column per aggregation, and you drop the group levels the same way:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 30],
})
stats = (
df.groupby("store")["sales"]
.rolling(2)
.agg(["mean", "max"])
.reset_index(level=0, drop=True)
)
df = df.join(stats.add_prefix("sales_"))
print(df.columns.tolist())
# ['store', 'sales', 'sales_mean', 'sales_max']add_prefix avoids a name clash if you join statistics for several columns.
Window options inside groups
Every option from the earlier chapters works the same way, but each group is treated as its own series. Two consequences follow.
min_periodsapplies per group. Withrolling(3, min_periods=1), each group gets a value from its first row, and the first value of store B does not borrow from store A.center=Trueputs theNaNvalues at both ends of each group, not only at both ends of the whole DataFrame.
Expanding windows follow the same pattern. df.groupby("store")["sales"].expanding().mean() gives a running mean that restarts at each group. For a plain running sum or maximum, groupby("store")["sales"].cumsum() and .cummax() are shorter and faster.
Time-based windows within groups
A time window such as "3D" needs the timestamps to be in sorted order within each group. The simplest setup is to sort by group and date, move the date into the index, and then group:
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-05",
"2024-01-01", "2024-01-03", "2024-01-04",
]),
"sales": [1, 2, 3, 10, 20, 30],
})
df = df.sort_values(["store", "date"]).set_index("date")
print(df.groupby("store")["sales"].rolling("3D").sum())
# store date
# A 2024-01-01 1.0
# 2024-01-02 3.0
# 2024-01-05 3.0
# B 2024-01-01 10.0
# 2024-01-03 30.0
# 2024-01-04 50.0
# Name: sales, dtype: float64Each window covers the interval (t - 3 days, t]. For store A on 2024-01-05, the window starts after 2024-01-02, so only that day's own row is inside and the sum is 3. The calendar gaps differ between stores, so the number of rows per window differs too. The result here is indexed by (store, date). If you need it back on the original rows, you must merge on those two keys, or use transform on a frame that keeps its original index.
Shift within groups to avoid leakage
A rolling feature that includes the current row leaks the current value into a model that predicts it. The usual remedy is .shift(1). With groups, where you put the shift matters.
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "A", "B", "B", "B", "B"],
"sales": [10, 20, 30, 40, 100, 200, 300, 400],
})
df["feature"] = df.groupby("store")["sales"].transform(
lambda s: s.rolling(2).mean().shift(1)
)
print(df["feature"].tolist())
# [nan, nan, 15.0, 25.0, nan, nan, 150.0, 250.0]The shift is inside the lambda, so it runs once per group. The first row of store B has no previous value in its own group, and feature is NaN there. If you computed the grouped rolling mean first and called df["avg"].shift(1) on the whole column, row 4 would receive the last rolling mean of store A. That is a boundary leak of the same kind as the one at the start of this chapter. When the rolling result is already a column, use df.groupby("store")["avg"].shift(1) instead.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Assigning the result raises a reindexing error | Group level still in the index, or duplicate row labels | `reset_index(level=0, drop=True)`, and make the index unique first |
| Values in the first row of a group are not `NaN` | Rolling was called without `groupby` | Call `groupby(...)` before `rolling` |
| A time window raises an error about monotonic order | Timestamps not sorted within a group | Sort by group and date before rolling |
| Result is a Series with a `(store, date)` index when you wanted the old index | Time-based index replaced the row labels | Keep the original labels and use `transform`, or merge on the keys |
| Wrong number of levels dropped | Several group keys | Drop one level per key, for example `level=[0, 1]` |
Exercises
Exercise
A DataFrame has columns sensor and temp, with rows from sensors "s1" and "s2" in alternating order and a default RangeIndex. Write code that adds a column temp_avg3 holding the 3-row rolling mean of temp for each sensor, with NaN for the first two rows of each sensor.
Show answer
df["tempavg3"] = df.groupby("sensor")["temp"].rolling(3).mean().resetindex(level=0, drop=True) An equivalent form is df["temp_avg3"] = df.groupby("sensor")["temp"].transform(lambda s: s.rolling(3).mean()). Both give NaN in the first two rows of each sensor, because each window needs three rows from the same sensor.
Exercise
You compute df["avg"] = df.groupby("store")["sales"].transform(lambda s: s.rolling(3).mean()) and then df["prevavg"] = df["avg"].shift(1). The first row of store B in prevavg is not NaN. Why, and how do you fix it?
Show answer
The shift runs on the whole column, so the first row of store B receives the last value of store A's avg. Shift inside each group instead: df["prev_avg"] = df.groupby("store")["avg"].shift(1). The first row of every store is then NaN.