Sub topic 15
Resampling with PeriodIndex
This chapter assumes you know DatetimeIndex.resample(): bins, aggregation, and ffill(). It also assumes you can build a Series with a datetime index. The new part is the PeriodIndex, a second kind of time index that changes how bins behave.
Timestamps and periods
A DatetimeIndex holds points in time, such as 2024-01-15 00:00. A PeriodIndex holds spans of time, such as "January 2024" or "the week of 1–7 January". Each element is a Period with a frequency.
This difference matters for resampling. With timestamps, pandas must decide which side of a bin edge a point belongs to, which is what closed, label, origin, and offset control. A period already knows which span it covers, so a monthly period always falls into exactly one quarterly period. Period data suits accounting-style series such as monthly revenue, quarterly GDP, or fiscal-year budgets, where the value describes the whole span.
Create a period index with pd.period_range(), or convert a datetime index with to_period().
Downsampling a PeriodIndex
Downsampling works the same way as before: call resample() with a coarser frequency, then aggregate. The result keeps a PeriodIndex.
import pandas as pd
monthly = pd.Series(
[1, 2, 3, 4, 5, 6],
index=pd.period_range("2024-01", periods=6, freq="M"),
)
print(monthly.resample("Q").sum())
daily = pd.Series(
range(10),
index=pd.period_range("2024-01-01", periods=10, freq="D"),
)
print(daily.resample("W").sum())The first result has two rows. 2024Q1 is 1+2+3 = 6 and 2024Q2 is 4+5+6 = 15. The index labels are periods, not timestamps.
The second result matches the weekly example from earlier in the tutorial. The values are 21 and 24. The labels are different. Instead of a Sunday timestamp, each row is labeled with the whole span it covers, for example 2024-01-01/2024-01-07. Weeks default to W-SUN, so a week runs Monday to Sunday.
Empty bins behave as they do for timestamps. A sum() over a quarter with no data returns 0, and sum(min_count=1) returns NaN instead.
Fiscal calendars
Many organizations do not use calendar years. A period frequency can carry an anchor that says which month ends the year. "Q-MAR" means quarters in a fiscal year that ends in March.
import pandas as pd
monthly = pd.Series(
range(1, 13),
index=pd.period_range("2024-01", periods=12, freq="M"),
)
fiscal = monthly.resample("Q-MAR").sum()
print(fiscal)January to March 2024 is the last quarter of the fiscal year that ends in March 2024. It is labeled 2024Q4 and sums to 6. April to June 2024 belongs to the next fiscal year, so it is labeled 2025Q1 and sums to 15. The two remaining quarters are 2025Q2 (24) and 2025Q3 (33).
The label uses the year in which the fiscal year ends. This is a common source of confusion, so check the first and last labels against your own calendar.
Upsampling and convention
Upsampling a period series raises a question that timestamps do not. When one quarterly value becomes three monthly rows, which month gets the original value? The convention argument answers this. It accepts "start" (the default) or "end".
import pandas as pd
quarterly = pd.Series(
[10.0, 20.0],
index=pd.period_range("2024Q1", periods=2, freq="Q"),
)
print(quarterly.resample("M", convention="start").asfreq())
print(quarterly.resample("M").ffill())
print((quarterly / 3).resample("M").ffill())With convention="start", each value lands on the first month of its quarter. asfreq() leaves the other months as NaN: January is 10, February and March are NaN, April is 20, and so on. With convention="end", each value lands on the last month of its quarter instead.
ffill() then repeats the value across the quarter, giving 10, 10, 10, 20, 20, 20. The fill methods from the upsampling chapters (ffill, bfill, interpolate) all work here.
The third line is about meaning, not mechanics. A quarterly total of 10 is a flow, a quantity that accumulates over time. Copying it into each month makes the monthly numbers sum to 30. Divide by 3 first if you want a monthly share. Stocks, such as a month-end balance or a rate, can usually be repeated unchanged.
Converting between timestamps and periods
Real data often arrives with timestamps. You have two routes to period bins.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=60, freq="D")
s = pd.Series(range(60), index=idx)
a = s.resample("MS").sum().to_period("M")
b = s.to_period("D").resample("M").sum()
print(a)
print(b)
print(b.to_timestamp())
print(b.to_timestamp(how="end"))Both routes give two months with sums 465 for January and 1305 for February. Route a bins with timestamps and then relabels the result. Route b converts first and bins as periods. Either works, and the choice mostly depends on which labels you want downstream.
to_period() alone does not aggregate. s.to_period("M") produces a monthly index with many duplicate entries, one per day. You still need resample() or groupby() to combine them.
to_timestamp() converts periods back to timestamps. By default it uses the start of each period. With how="end" it uses the last instant of the period, which is the final nanosecond of the last day. Use how="end" when you want to align a monthly total with the date it became known.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Frequency error with `"ME"` or `"QE"` | Offset aliases passed to a `PeriodIndex` | Use `"M"`, `"Q"`, `"Y"` |
| Fiscal quarters labeled with an unexpected year | The label uses the year the fiscal year ends | Check the anchor, such as `"Q-MAR"`, and compare the first label |
| Monthly totals add up to 3 times the quarterly total | A flow value was upsampled with `ffill()` | Divide the flow by the number of sub-periods first |
| Duplicate monthly labels after `to_period("M")` | Conversion relabels rows and does not aggregate | Follow with `resample` or `groupby(level=0)` |
| Calling `tz_localize()` fails | A `PeriodIndex` has no time zone | Resample in time zones with timestamps, then convert |
| NaN at the start after upsampling with `convention="end"` | No earlier value exists to fill forward | Use `bfill()` or the default `"start"` |
When to choose periods
Use a PeriodIndex when the value belongs to a whole calendar span and you want labels such as 2024Q1 or a fiscal-year anchor. Periods can also represent years outside the range of nanosecond timestamps, which is roughly 1677 to 2262.
Stay with timestamps when you need time zones or daylight saving handling, or when bins need an origin or offset. Timestamps also fit data with irregular event times.
Exercise
A monthly Series m has a PeriodIndex starting at 2024-01 for 12 months, with values 1 to 12. You call m.resample("Q-NOV").sum(). In which fiscal quarter does December 2024 fall, and why might the label surprise you?
Show answer
With Q-NOV the fiscal year ends in November. December 2024 therefore starts a new fiscal year, ending November 2025, and is part of the first quarter of that year. It is labeled 2025Q1, one year later than the calendar year, because the label uses the year in which the fiscal year ends.
Exercise
You have a quarterly Series rev with the PeriodIndex pd.period_range("2024Q1", periods=4, freq="Q") holding quarterly revenue totals. Write one expression that produces monthly revenue so the monthly values still sum to each quarterly total. Why is rev.resample("M").ffill() wrong for this?
Show answer
Use (rev / 3).resample("M").ffill(). Plain ffill() copies the full quarterly total into each of the three months, so the monthly values sum to three times the quarterly total. Dividing by 3 first spreads the flow evenly across the months.