Sub topic 13
Grouping by time periods with pd.Grouper
This chapter assumes you can build a DataFrame, select columns, and run a basic groupby(...).sum(). It also assumes you know what a datetime column is. The goal is to group rows into calendar periods such as months or weeks without writing any date arithmetic yourself.
Why time needs its own grouper
Dates are rarely repeated exactly. Grouping by a raw timestamp column gives one group per distinct timestamp, which is useless for a summary. What you want is a group per period: all of January, all of February, and so on.
pd.Grouper lets you describe that rule. You give it the datetime column (key) and a frequency (freq), and groupby bins each row into the matching period.
A monthly total
import pandas as pd
sales = pd.DataFrame({
"date": pd.to_datetime(["2024-01-05", "2024-01-20", "2024-02-03", "2024-02-15"]),
"revenue": [100.0, 50.0, 80.0, 20.0],
})
monthly = sales.groupby(pd.Grouper(key="date", freq="MS"))["revenue"].sum()
print(monthly)
# date
# 2024-01-01 150.0
# 2024-02-01 100.0
# Freq: MS, Name: revenue, dtype: float64"MS" means month start. Each group is labeled by the first day of its month. The result is an ordinary Series indexed by those labels, so everything you learned about result shape still applies.
Common frequency codes
| Code | Meaning | Label of each group |
|---|---|---|
| `D` | Calendar day | The day |
| `W` | Week, ending Sunday | The Sunday that ends the week |
| `MS` | Month | First day of the month |
| `QS` | Quarter | First day of the quarter |
| `YS` | Year | January 1 |
Month-end ME and year-end YE also exist, in pandas 2.2 and later. Older versions spelled them M and Y. Check your installed version if a code raises an error.
How the bins are built
The diagram shows what happens when you group the example above.
This is the same split-apply-combine pattern as before. Only the splitting rule changed.
Combining time with another key
You can pass a Grouper inside a list next to ordinary keys. This gives one row per period and category pair.
orders = pd.DataFrame({
"date": pd.to_datetime(["2024-01-05", "2024-01-20", "2024-02-03", "2024-02-15"]),
"region": ["North", "South", "North", "North"],
"revenue": [100.0, 50.0, 80.0, 20.0],
})
result = orders.groupby([pd.Grouper(key="date", freq="MS"), "region"])["revenue"].sum()
print(result)
# date region
# 2024-01-01 North 100.0
# South 50.0
# 2024-02-01 North 100.0
# Name: revenue, dtype: float64The result has a MultiIndex. Add .reset_index() if you prefer flat columns.
Gotchas
- The column must have a datetime dtype. If your dates are strings, convert them first with
pd.to_datetime. OtherwiseGrouperraises aTypeError. - Empty periods are kept. If no rows fall in March, a March group still appears, with
0.0for a sum. This is useful for continuous charts but can surprise you if you expected only observed periods. - If the dates are in the index instead of a column, omit
key. Usepd.Grouper(freq="MS")and pandas reads the index.
Exercise
You have a DataFrame df with a datetime column ts and a numeric column amount. Write the expression that returns the total amount for each calendar week. What label does each week get with the default weekly frequency?
Show answer
df.groupby(pd.Grouper(key="ts", freq="W"))["amount"].sum(). With "W", each group is labeled by the Sunday that ends the week.
Exercise
Your date column contains strings such as "2024-01-05", and pd.Grouper(key="date", freq="MS") fails. What is the likely cause and the fix?
Show answer
The column has an object (string) dtype, not a datetime dtype. Convert it first with df["date"] = pd.to_datetime(df["date"]), then group again.