Time-Based Grouping
Resampling is perfect for rolling a series up to a coarser frequency. But often you want to group by a calendar attribute, like day of week or month name, or combine a time bucket with another column such as region. This lesson covers Grouper, grouping by extracted date parts, and combining time with categorical keys.
What You'll Learn
- How to group by month or week while keeping other group keys
- How to group by extracted date parts like weekday or hour
- How to use
pd.Grouperto time-bucket inside a GroupBy - How to build a time-plus-category summary
Grouping by Extracted Date Parts
Sometimes the question is not "each January" but "all Mondays" or "every 9 a.m. hour." Extract the date part with the .dt accessor and group on it. This aggregates across the whole series by calendar attribute.
Because day_name() repeats across weeks, the groups collect every Monday together, every Tuesday together, and so on.
pd.Grouper: Time Buckets Inside GroupBy
When you want true calendar buckets (each actual month, not "all Januaries") combined with another key, use pd.Grouper(freq=...). It behaves like resample but plugs into a regular GroupBy so you can mix it with other columns.
Here pd.Grouper(key='date', freq='ME') makes the monthly buckets, and 'region' adds the second grouping level. The result is monthly totals broken out by region, something plain resample cannot do alone.
Grouper With a DatetimeIndex
If the dates are already in the index, you can omit key and let Grouper use the index directly.
Pivoting Time and Category for Readability
A time-plus-category result is often easier to read as a wide table. Use unstack to pivot the category onto columns.
Exercise: Average by Weekday
Exercise: Monthly Totals by Group
Key Points
- Extract a date part with
.dt(orindex.day_name()) to group across the calendar, like all Mondays pd.Grouper(freq=...)makes true time buckets that plug into a regular GroupBy- Combine
pd.Grouperwith another column to break a time series out by category - Use
key=when the date is a column, or omit it when the date is the index unstackpivots the category onto columns for a readable wide table

