Resampling

Group by time period without building the key yourself.

resample is group-by for time

With a datetime index, resample buckets rows into periods -- days, weeks, months -- and takes a summary of each.

import pandas as pd

idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-02-01"])
s = pd.Series([1, 2, 5], index=idx)
print(s.resample("MS").sum().tolist())

Empty periods appear

Unlike a group-by, resample produces every period in the range, including those with no rows. That is what makes a timeline continuous rather than jumping over the quiet months.

import pandas as pd

idx = pd.to_datetime(["2024-01-01", "2024-03-01"])
s = pd.Series([1, 1], index=idx)
print(s.resample("MS").sum().tolist())

Exercise

Try It Yourself

Write monthly_totals(s) that takes a Series indexed by date and returns a list of monthly totals, including months with nothing in them.

Press Run to see output

Check Your Understanding