to_period()
noun
say it: “too PEER-ee-ud” /tu ˈpɪriəd/
A pandas method that turns each date into the period it falls in, such as its month or year, so rows from the same period can be grouped.
What does to_period() do in pandas?
to_period() is a .dt method that turns each date into the period it falls in, such as its month ("M"), so rows
can be grouped by month. June 3 and June 28 both become 2026-06.
import pandas as pd
orders = pd.DataFrame({"ordered_at": pd.to_datetime(["2026-06-03", "2026-06-28", "2026-07-02"]),
"total": [20.0, 15.0, 30.0]})
print(orders.groupby(orders["ordered_at"].dt.to_period("M"))["total"].sum())
# ordered_at
# 2026-06 35.0
# 2026-07 30.0
In a sentence
- “to_period() turned every order date into its month.”
- “Grouping on to_period() gave one total for June and one for July.”
Level: Journeyman · More Python terms at this level
Updated