Date Parts

Year, month and weekday are columns you can group by.

Pulling a part out

Once a column is really a date, its parts are one attribute away, and each is an ordinary column you can group or filter on.

import pandas as pd

s = pd.to_datetime(pd.Series(["2024-03-01", "2024-03-15"]))
print(s.dt.year.tolist())
print(s.dt.month.tolist())

Grouping by a part

"How many per month" is a group-by on a derived column, which is why the parts matter.

import pandas as pd

df = pd.DataFrame({"day": pd.to_datetime(["2024-01-05", "2024-02-01"]), "n": [1, 2]})
print(df.groupby(df["day"].dt.month)["n"].sum().to_dict())

Exercise

Try It Yourself

Write by_month(df) that takes a table with a datetime day column and a numeric n, and returns a dictionary of month number to the total of n.

Press Run to see output

Check Your Understanding