Monthly totals with to_period
A pandas exercise from Pandasdrill. Solve it with a Python editor in your browser running real pandas, and it is checked the moment you submit.
The task
Total `amount` per calendar month, indexed by a monthly Period such as 2024-01. Unlike resample, only months that have at least one transaction should appear.
What this exercise teaches
to_period("M") maps every date to a Period like 2024-01, which keeps the year and the month together, so grouping by it never mixes January 2024 with January 2025 the way dt.month does. groupby only creates groups that exist in the data, which is why empty months are skipped; resample fills them with 0.
A hint if you get stuck
dt.to_period("M") turns each date into its month. A Series can be passed straight to groupby.
Try it now, free, no account needed
The first 15 tasks on Pandasdrill are free. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro adds timed mode and the certificate.
Open this exercise