A Datetime Index

Putting time on the index unlocks slicing by period.

set_index on a date column

With time on the index, a string is enough to select a period, which reads far better than two comparisons.

import pandas as pd

df = pd.DataFrame({"day": pd.to_datetime(["2024-01-05", "2024-02-01"]), "n": [1, 2]})
df = df.set_index("day")
print(df.loc["2024-01"]["n"].tolist())

Order matters

Slicing a time index expects it sorted. Sorting once after setting the index saves a confusing error later.

import pandas as pd

df = pd.DataFrame({"day": pd.to_datetime(["2024-02-01", "2024-01-05"]), "n": [2, 1]})
df = df.set_index("day").sort_index()
print(df["n"].tolist())

Exercise

Try It Yourself

Write month_total(df, month) where df has a datetime day column and a numeric n, and month is a string like "2024-01". Return the total of n in that month.

Press Run to see output

Check Your Understanding