Sub topic 13
Resampling within groups
This chapter assumes you can resample a single series with resample(), including on= for a date column, and that you know groupby() basics. Here you combine the two so that each group, such as each store or sensor, is resampled separately.
Why grouping matters
resample() on a whole DataFrame mixes every row into the same bins. If your data holds several entities, that adds them together. Monthly sales for two stores would collapse into one number per month. You usually want one monthly figure per store.
The fix is to call groupby() first and resample() second. pandas splits the rows by group, resamples each piece, and stacks the results.
Grouped resampling with on=
Here is a table of sales for two stores. The date column is a regular column, not the index.
import pandas as pd
df = pd.DataFrame(
{
"date": pd.to_datetime(
["2024-01-05", "2024-01-20", "2024-02-03", "2024-01-10", "2024-03-15"]
),
"store": ["A", "A", "A", "B", "B"],
"sales": [100, 150, 80, 60, 90],
}
)
monthly = df.groupby("store").resample("MS", on="date")["sales"].sum()
print(monthly)The output has a two-level index, store and the month start:
store date
A 2024-01-01 250
2024-02-01 80
B 2024-01-01 60
2024-02-01 0
2024-03-01 90
Name: sales, dtype: int64Select ["sales"] before aggregating. Otherwise the store and date grouping columns can end up inside the aggregation, which raises warnings or errors in recent pandas versions.
If the date is already the index, skip on= and write df.groupby("store")["sales"].resample("MS").sum().
Several aggregations per group
Resampler objects accept the same aggregation tools as before. Named aggregation gives readable column names:
summary = df.groupby("store").resample("MS", on="date").agg(
total=("sales", "sum"),
orders=("sales", "count"),
)
print(summary)For store B in February the result is total 0 and orders 0. The empty-bin rules from the earlier chapter still apply inside each group. Pass min_count=1 to sum() if you want NaN instead of 0.
Each group gets its own date range
Store A has no March row in the result above, but store B has a February row with a zero. Each group is resampled only between its own first and last timestamps. Bins before a group's first row or after its last row are not created.
Using pd.Grouper
You can also put the time bins inside groupby() with pd.Grouper:
alt = df.groupby(["store", pd.Grouper(key="date", freq="MS")])["sales"].sum()
print(alt)This form is handy when you group by several keys at once. It bins time with the same frequency rules as resample(). It also keeps the grouping in one place and works with transform(). Compare it with the resample result on your own data, because the two forms can differ in how they treat empty bins.
Common errors
TypeErrorabout DatetimeIndex. The date column is still strings. Convert it withpd.to_datetime()first.- Unexpected extra columns or warnings. Select the value columns before aggregating.
- Different month counts per group. This is expected, as described above. Reindex if you need a shared grid.
- A wide table is needed. Call
.unstack("store")on the result to get one column per store.
Exercise
Using the df above, write one expression that gives the mean sales per store per month, with one row per store and month. What happens to store A in March?
Show answer
df.groupby("store").resample("MS", on="date")["sales"].mean(). Store A has no March row, because each group is resampled only between its own first and last dates (January to February). Store B's February row is NaN, since the mean of an empty bin is undefined.