Sub topic 13
Resampling within groups
This chapter assumes you can already call resample() on a single time series. It also assumes you know how to use groupby() and what a MultiIndex is. The task here is to resample data that holds several entities at once, such as stores, sensors, or users, so that each entity gets its own bins.
Why a plain resample is not enough
Suppose one table holds sales for two stores. Calling df.resample("MS").sum() mixes both stores into the same monthly bins. You get one total per month and lose the per-store figures.
You need to split the rows by store first, then resample each piece. pandas gives you two ways to do that:
df.groupby("store").resample(...), which is the usual choice.df.groupby(pd.Grouper(key="date", freq=...)), which is useful when you want to mix a time bin with other grouping keys.
The basic pattern
import pandas as pd
df = pd.DataFrame(
{
"date": pd.to_datetime(
[
"2024-01-10", "2024-01-20", "2024-03-05",
"2024-01-15", "2024-02-15", "2024-03-15", "2024-04-15",
]
),
"store": ["A", "A", "A", "B", "B", "B", "B"],
"sales": [5, 7, 4, 3, 6, 9, 1],
}
)
monthly = df.groupby("store").resample("MS", on="date")["sales"].sum()
print(monthly)The result is a Series with a two-level index. The first level is store and the second is the month-start timestamp.
- Store A has
2024-01-01= 12,2024-02-01= 0, and2024-03-01= 4. - Store B has four months: 3, 6, 9, and 1.
The on="date" argument works here the same way it does for an ungrouped resample. The column does not need to be the index.
Each group gets its own time range
The most important rule is that resample() runs independently inside every group. Each group's bins span only from that group's first timestamp to its last.
In the example above, store A has no April row, so its result stops at March. Store B has an April row, so its result continues. Inside A's range, February still appears with a sum of 0. That bin is empty, and the default sum() returns 0 for empty bins, as covered in the chapter on empty bins.
This leads to two consequences:
- The groups may have result indexes of different lengths.
- Bins that fall outside a group's own range are not created at all. They are missing, not zero or NaN.
If you need every group on the same grid, reshape or reindex the result.
wide = monthly.unstack("store")
print(wide.fillna(0))unstack("store") turns the stores into columns. The April value for store A is missing, so it becomes NaN, and fillna(0) replaces it. Whether 0 is the right fill depends on the data. For sales, no row usually means no sales. For a sensor reading, NaN is more honest.
Another option is to build the full grid explicitly and reindex:
grid = pd.MultiIndex.from_product(
[["A", "B"], pd.date_range("2024-01-01", "2024-04-01", freq="MS")],
names=["store", "date"],
)
full = monthly.reindex(grid, fill_value=0)
print(full)The names match the existing index levels, so the reindex lines up correctly. Every store now has four rows.
Bin alignment is per group too
Anchored frequencies such as "MS" or "W" produce the same bin edges for every group. Fixed frequencies such as "2D" or "6h" do not behave that way by default. They use origin="start_day", which is midnight of each group's own first day.
Take a group that starts on January 1 and another that starts on January 2. With "2D", the first group's bins begin on odd dates and the second group's bins begin on even dates. Their rows then cannot be compared side by side.
To force one shared alignment, pass an explicit origin:
aligned = (
df.groupby("store")
.resample("2D", on="date", origin=pd.Timestamp("2024-01-01"))["sales"]
.sum()
)
print(aligned)Every group now uses bin edges at January 1, 3, 5, and so on. This matters whenever you plan to compare or sum groups after resampling.
Several aggregations per group
Named aggregation works on the grouped resampler. Each keyword becomes an output column.
summary = df.groupby("store").resample("MS", on="date").agg(
total=("sales", "sum"),
orders=("sales", "count"),
)
print(summary)The index is again (store, date). Store A's February row has total 0 and orders 0, because count() returns 0 for an empty bin. Choose your aggregation with this in mind. A mean over an empty bin returns NaN, while a sum returns 0.
Upsampling inside groups
Filling methods also run per group. This matters because a forward fill must never carry a value from one store into another.
snap = pd.DataFrame(
{
"date": pd.to_datetime(
["2024-01-01", "2024-01-04", "2024-01-02", "2024-01-03"]
),
"store": ["A", "A", "B", "B"],
"stock": [10, 7, 5, 4],
}
)
daily = snap.groupby("store").resample("D", on="date")["stock"].ffill()
print(daily)Store A gets four daily rows with values 10, 10, 10, 7. Store B gets two rows with values 5 and 4. Because each group is processed alone, B's first row is never filled with A's data. B also does not get rows for January 1 or January 4, since those fall outside its range.
Common errors and gotchas
- Grouping column warnings. When you call
groupby(...).resample(...)on a whole DataFrame and then useapply(), recent pandas versions may warn that the grouping column is included in the operation. Select the columns you need first, for example["sales"], to avoid this. - Forgetting
on=. If the dates are in a column and you leave outon="date", pandas raises aTypeErrorbecause the index is not aDatetimeIndex. - Flat output wanted. The
MultiIndexresult is awkward to merge or plot. Call.reset_index()to get ordinary columns. - Assuming equal lengths. Never assume each group has the same number of bins. Check with
.groupby(level="store").size(). - Mixed fills. Filling the unstacked table with 0 hides the difference between "zero sales" and "no data". Decide which one you mean.
Choosing an approach
| Goal | Approach |
|---|---|
| One time series per entity, each on its own range | `df.groupby(key).resample(rule, on=...)` |
| Same bins for every entity | Anchored frequency or explicit `origin` |
| Entities as columns, shared grid | `.unstack(key)` after resampling |
| Time bins combined with other keys | `groupby([key, pd.Grouper(key="date", freq=...)])` |
| Every entity covers the full period | `reindex` with `MultiIndex.from_product` |
When you use the pd.Grouper form, check the output on your own data. Compare which empty bins appear with what the resample form gives you.
Exercise
A DataFrame has columns date, sensor, and temp. Sensor X reports from January 1 to January 10, and sensor Y from January 5 to January 10. You run df.groupby("sensor").resample("D", on="date")["temp"].mean(). How many rows does sensor Y get, and how would you give both sensors the same ten daily rows?
Show answer
Sensor Y gets six rows, January 5 to January 10, because each group is resampled only across its own first and last timestamps. To give both sensors the same ten rows, reindex the result with pd.MultiIndex.from_product([["X", "Y"], pd.date_range("2024-01-01", "2024-01-10")], names=["sensor", "date"]). You can also call .unstack("sensor") and reindex the rows with the full date range. The new rows hold NaN unless you pass fill_value.
Exercise
Two groups use resample("3D", on="date") with the default origin. Group P starts on January 1 and group Q starts on January 2. Why can their bins not be lined up, and what argument fixes it?
Show answer
The default origin="start_day" anchors the bins at midnight of each group's own first day, so P's bins start on January 1, 4, 7 and Q's on January 2, 5, 8. Passing the same explicit origin, such as origin=pd.Timestamp("2024-01-01"), gives both groups the same bin edges.