Sub topic 13
Grouping by time periods with pd.Grouper
This chapter assumes you can build a DataFrame, select columns, and use groupby with sum and agg. It also assumes you know what a DatetimeIndex is and have seen pd.to_datetime. If those are new, review them first.
Time series data rarely repeats exact timestamps, so grouping by the raw column gives one group per row. You usually want calendar buckets such as days, weeks, months, or quarters. pd.Grouper is an object that tells groupby to bin a datetime key by a frequency instead of by exact value.
How binning works
pd.Grouper(key="date", freq="MS") does three things. It finds the earliest and latest timestamps and builds a regular sequence of bin edges from the frequency. It assigns each row to the bin containing its timestamp. Then it labels each bin, by default with the bin's start for most frequencies.
Grouping a column by month
Use key to name the datetime column. The column must have a datetime dtype, so convert strings with pd.to_datetime first.
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: float64MS means month start. Each label is the first day of its month, and the result index is a DatetimeIndex with that frequency attached.
Common frequency aliases
| Alias | Bin | Label |
|---|---|---|
| `D` | Calendar day | Midnight of that day |
| `W` (same as `W-SUN`) | Week ending Sunday | The Sunday that ends the week |
| `MS` | Calendar month | First day of the month |
| `ME` | Calendar month | Last day of the month |
| `QS` | Calendar quarter | First day of the quarter |
| `YS` | Calendar year | January 1 |
| `h` | Hour | Start of the hour |
Grouping by the index
If the time values are in a DatetimeIndex, omit key. Grouper then uses the index.
import pandas as pd
ts = pd.Series(
range(1, 11),
index=pd.date_range("2024-01-01", periods=10, freq="D"),
)
print(ts.groupby(pd.Grouper(freq="W")).sum())
# 2024-01-07 28
# 2024-01-14 27
# Freq: W-SUN, dtype: int64January 1, 2024 is a Monday. The first week ends on Sunday, January 7, and holds the values 1 through 7. The default for W is to label each bin with its right edge, which is why the labels are Sundays.
Controlling edges and labels
Two parameters decide where a boundary timestamp goes and what the bin is called.
closedis the side of the bin that includes its edge:"left"or"right".labelis which edge names the bin:"left"or"right".
For weeks that start on Monday and are named by that Monday, anchor on W-MON and set both to "left".
import pandas as pd
ts = pd.Series(
range(1, 11),
index=pd.date_range("2024-01-01", periods=10, freq="D"),
)
weekly = ts.groupby(pd.Grouper(freq="W-MON", closed="left", label="left")).sum()
print(weekly)
# 2024-01-01 28
# 2024-01-08 27
# Freq: W-MON, dtype: int64Most frequencies, such as MS, D, and h, already default to left-closed, left-labeled bins. Month-end, quarter-end, year-end, and weekly (W) frequencies default to the right edge. Setting both parameters explicitly makes the intent clear to readers.
Empty periods appear in the result
Bins are built as a complete range, so a period with no rows is still a group. Aggregations that have a natural empty value return it.
import pandas as pd
gap = pd.DataFrame({
"date": pd.to_datetime(["2024-01-05", "2024-03-10"]),
"revenue": [100.0, 50.0],
})
print(gap.groupby(pd.Grouper(key="date", freq="MS"))["revenue"].sum())
# date
# 2024-01-01 100.0
# 2024-02-01 0.0
# 2024-03-01 50.0
# Freq: MS, Name: revenue, dtype: float64February has no rows and shows 0.0. With mean, min, or max the empty bin would be NaN. This is usually what you want for a continuous time axis, but note that a 0.0 from an empty period is indistinguishable from a real zero. Use size() alongside if the difference matters.
Combining time with other keys
Put a Grouper in a list together with ordinary keys. The time key becomes one level of a MultiIndex.
import pandas as pd
sales = 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 = sales.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: float64With several keys, only combinations that occur appear, so South has no February row. Empty-bin filling applies to the time level on its own. If you need every region in every month, call unstack with fill_value=0 or reindex against a full product of the levels.
as_index=False and reset_index() work as they do for other keys and turn the time level back into a column.
Alternatives and how they compare
You can get calendar buckets without Grouper. The two common routes are resample and the .dt accessor.
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],
})
# Same bins as Grouper(freq="MS")
print(sales.resample("MS", on="date")["revenue"].sum())
# Group by a monthly Period computed from the column
print(sales.groupby(sales["date"].dt.to_period("M"))["revenue"].sum())
# date
# 2024-01 150.0
# 2024-02 100.0
# Freq: M, Name: revenue, dtype: float64Choose by the situation:
- Grouper fits when time is one key among several, because it sits in a
groupbylist. - resample fits when time is the only grouping axis. It gives the same bins and adds methods such as
ffill,asfreq, andinterpolate. - dt.to_period fits when you want period labels like
2024-01and the periods don't need to be a continuous range. It does not fill empty periods. - dt.month or dt.year alone is risky.
dt.monthmerges January 2023 with January 2024. Group by[dt.year, dt.month]if you take this route.
Edge cases and pitfalls
- The column is not datetime. A string or object column raises a
TypeErrorabout needing aDatetimeIndex,TimedeltaIndex, orPeriodIndex. Convert withpd.to_datetimefirst. - Missing timestamps. Rows whose time value is
NaTare dropped from the groups, as with other missing keys under the defaultdropna=True. - Both
keyand an index.keyselects a column. Without it,Grouperuses the index and fails if the index is not time-like. - Time zones. Bins follow the column's time zone, so a day boundary is local midnight for tz-aware data. Convert with
tz_convertbefore grouping if you want a different boundary. - Unsorted data.
Grouperdoes not require sorted input, and the result is ordered by time. - Very fine frequencies over wide ranges. Because empty bins are created,
freq="s"across several years builds millions of groups. Check the span before choosing a small frequency.
Exercise
A DataFrame orders has a datetime column placed and a numeric column amount. Write one expression that returns the total amount for each calendar quarter, labeled by the first day of the quarter. What happens to a quarter in which no orders were placed between the first and last order?
Show answer
orders.groupby(pd.Grouper(key="placed", freq="QS"))["amount"].sum() The quarter still appears in the result because Grouper builds a complete range of bins. Its total is 0.0, since the sum of an empty group is zero. With mean it would be NaN.
Exercise
You group a daily Series by pd.Grouper(freq="W") and the labels are Sundays, but your business weeks start on Monday and you want each week labeled by its Monday. Which freq, closed, and label values do you use?
Show answer
freq="W-MON", closed="left", label="left". Each bin then runs from a Monday up to, but not including, the next Monday, and is named by its starting Monday.