Sub topic 12
Periods and PeriodIndex for calendar spans
This chapter assumes you can create a Series with a DatetimeIndex, use pd.to_datetime, and group with groupby. It also assumes you know the difference between a Timestamp and a Timedelta from earlier chapters.
What a Period is
A Timestamp marks one instant. A Period marks a whole span of calendar time, such as a month, a quarter, or a year. The span is defined by a start and a frequency.
import pandas as pd
p = pd.Period("2024-03", freq="M")
print(p.start_time, p.end_time)
print(p + 1)
print(p.asfreq("D", how="end"))start_time is 2024-03-01 00:00:00. end_time is 2024-03-31 23:59:59.999999999, the last nanosecond of the month. Adding an integer moves the Period by that many units of its own frequency, so p + 1 is 2024-04. The asfreq call converts the month to a day Period, and how="end" picks the last day, 2024-03-31.
Why use Periods instead of Timestamps
Use a Period when the span is the thing you mean. "March 2024 sales" refers to a month, not to midnight on March 1. A Period also never needs you to decide which instant stands for the span.
Periods help in these cases:
- Reporting by month, quarter, or fiscal year.
- Joining tables that are keyed by month.
- Comparing spans without worrying about month lengths.
| Type | Represents | Example |
|---|---|---|
| Timestamp | One instant | `2024-03-01 09:30` |
| Timedelta | A duration | `2 days 03:00:00` |
| Period | A calendar span | `2024-03` (month) |
Building a PeriodIndex
A PeriodIndex is an index made of Periods that all share one frequency. You can build one directly with pd.period_range, or convert an existing DatetimeIndex with to_period.
import pandas as pd
months = pd.period_range("2024-01", periods=4, freq="M")
print(months)
ts = pd.Series(
[10, 25, 40],
index=pd.to_datetime(["2024-03-01 09:30", "2024-03-02 14:45", "2024-03-05 08:00"]),
)
print(ts.index.to_period("D"))Each timestamp is truncated to the span that contains it. The time of day is dropped when you convert to a daily Period.
Grouping by calendar span
The most common use is grouping a time series by month. Convert the index with to_period, then group on the index level.
monthly = ts.to_period("M").groupby(level=0).sum()
print(monthly)All three rows fall in March, so the result has one row, 2024-03, with the value 75. The index keeps its Period type, so the labels read as months rather than as month-end dates.
resample("ME").sum() gives a similar total, but its labels are Timestamps at month end. Choose Periods when you want labels that name the span.
Converting back to Timestamps
Many plotting and merging steps expect a DatetimeIndex. Use to_timestamp to go back.
print(monthly.index.to_timestamp())
print(monthly.index.to_timestamp(how="end"))By default you get the first instant of each span. With how="end" you get the last instant.
Common errors
- Mixing frequencies. Subtracting a monthly Period from a daily one raises an error. Convert one side with
asfreqfirst. - Time zones are dropped.
to_periodon a tz-aware index emits a warning and discards the zone. Convert to the zone you want first, then callto_period. - Out-of-range dates. Periods are stored as integer counts of the frequency. Span arithmetic is cheap, but it is not the same as Timestamp arithmetic. Adding a Timedelta to a Period raises an error unless the Timedelta is a multiple of the Period's frequency.
Exercise
You have a Series ts indexed by timestamps. Write one expression that returns the count of rows per calendar quarter, with the index labeled by quarter (for example 2024Q1).
Show answer
ts.to_period("Q").groupby(level=0).count(). The to_period("Q") call converts each timestamp to the quarter that contains it, and groupby(level=0) groups on that PeriodIndex.