Sub topic 8
Rolling windows within groups
This chapter assumes you know rolling(window), min_periods, and basic groupby. It shows how to keep a window inside each group, such as one store or one sensor, and how to put the result back on the original rows.
Why a plain rolling window fails on grouped data
Suppose one DataFrame holds sales for several stores stacked on top of each other. A plain rolling(2).mean() treats the whole column as one sequence. The first row of store B would be averaged with the last row of store A, which is meaningless.
The fix is to split by group first and roll inside each group. Each group gets its own window, and each group starts with its own leading NaN values.
Calling rolling after groupby
Call rolling on the grouped column, not on the DataFrame before grouping.
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 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 A 2 1.5
# 2 A 3 2.5
# 3 B 10 NaN
# 4 B 20 15.0
# 5 B 30 25.0Row 3 is the first row of store B. It is NaN because store B has only one row so far. It does not borrow store A's last value.
Why reset_index is needed
groupby(...).rolling(...) returns a result with a two-level index. The first level is the group key and the second is the original row label. You cannot assign that result to a new column directly, because its index does not match the DataFrame's index.
reset_index(level=0, drop=True) removes the group level. What remains is the original row labels, so pandas aligns the values back onto the right rows.
Keeping the original row order with transform
The reset_index approach relies on the original index being unique. If two rows share a label, alignment fails or gives wrong results. A safer option is transform, which returns a result with the same index and order as the input:
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)
# 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.0Here the stores are interleaved, and each row still gets the average of its own store's last two values. The cost is that the lambda runs once per group in Python, which is slower than the built-in rolling path when there are many groups.
Using the other window options per group
Every option from the earlier chapters works the same way inside a group. For example, min_periods=1 removes the leading NaN in each group:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 30],
})
out = (
df.groupby("store")["sales"]
.rolling(2, min_periods=1)
.sum()
.reset_index(level=0, drop=True)
)
print(out.tolist())
# [1.0, 3.0, 5.0, 10.0, 30.0, 50.0]The same applies to expanding(), which gives a running total or running maximum that restarts for each group.
Common errors
- Rolling before grouping. Windows cross group boundaries and mix data from different entities. Always put
groupbyfirst. - Assigning without dropping the group level. You get a misaligned column full of
NaN, or an error about the index. Usereset_index(level=0, drop=True)ortransform. - Duplicate index labels. Alignment by label becomes ambiguous. Reset the index first, or use
transform. - Unsorted rows. The window follows row order, so an unsorted group produces averages over the wrong neighbors.
- Expecting a group to fill its first rows. A group with fewer rows than the window gives only
NaNunless you setmin_periods.
Exercise
A DataFrame has columns "sensor" and "reading", and you want a 3-row rolling mean of "reading" for each sensor. The first two rows of every sensor are NaN, but you want a value as soon as one reading exists. What code produces this as a new column, aligned to the original rows?
Show answer
df["avg3"] = df.groupby("sensor")["reading"].rolling(3, minperiods=1).mean().resetindex(level=0, drop=True). The groupby keeps windows inside each sensor, minperiods=1 removes the leading NaN values, and resetindex(level=0, drop=True) drops the sensor level so the result aligns with the original rows.