Sub topic 1
Start with a DatetimeIndex
Prerequisites
This chapter assumes you can:
- Write basic Python.
- Build a pandas
SeriesorDataFrame. - Select rows and columns with
[],.loc, andset_index(). - Read a date such as
2024-01-15and tell the year, month, and day apart.
Why resample() needs time-aware labels
resample() sorts rows into time bins, such as weeks or months. To do that, pandas must know where each row sits on the calendar. A DatetimeIndex stores each row label as a timestamp, so pandas can compare and group rows by time. A plain index of strings or integers has no calendar meaning.
If the index is not time-aware, resample() raises an error:
import pandas as pd
s = pd.Series([1, 2, 3], index=["2024-01-01", "2024-01-02", "2024-01-03"])
try:
s.resample("W").sum()
except TypeError as err:
print(type(err).__name__)
print(err)The index looks like dates, but it holds strings. Pandas does not guess.
Converting a column to a DatetimeIndex
Data usually arrives with dates in a column, often read from a CSV file as text. Fixing this takes three steps:
- Parse the column with
pd.to_datetime(). - Make it the index with
set_index(). - Sort the index with
sort_index().
import pandas as pd
df = pd.DataFrame(
{
"date": ["2024-01-03", "2024-01-01", "2024-01-02"],
"sales": [30, 10, 20],
}
)
print(df["date"].dtype)
df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date").sort_index()
print(type(df.index).__name__)
print(df.resample("D").sum())The first print shows object, which means text. After conversion, the index type is DatetimeIndex and resample("D") works.
Parsing problems to expect
Real data is rarely clean. These cases cause most failures.
- Ambiguous formats.
03/04/2024can mean March 4 or April 3. Passformat="%d/%m/%Y"(or the matching pattern) so pandas does not guess. - Invalid values. By default, one bad string makes
to_datetime()raise an error. Useerrors="coerce"to turn bad values intoNaT("not a time"), then decide what to do with those rows. - Unsorted rows. Resampling on an unsorted index can give surprising results. Call
sort_index()first. - Duplicate timestamps. Duplicates are allowed.
resample()will aggregate them into the same bin, but you may want to check whether they are mistakes.
import pandas as pd
raw = pd.Series(["2024-01-01", "oops", "2024-01-03"])
parsed = pd.to_datetime(raw, errors="coerce")
print(parsed)
print(parsed.isna().sum())This prints two valid timestamps and one NaT, then the count 1.
Checking your result
Before you resample, confirm the index with df.index. You want to see DatetimeIndex and a datetime64 dtype. Also check df.index.is_monotonic_increasing, which is True when the index is sorted.
Exercise
A DataFrame has a column day containing strings like "2024-02-01". Calling df.resample("W").sum() raises a TypeError. Write the lines that fix the problem, and explain why the error happened.
Show answer
Run df["day"] = pd.to_datetime(df["day"]), then df = df.set_index("day").sort_index(). The error happened because the index was not a DatetimeIndex. Strings, even ones that look like dates, give pandas no calendar to build bins from.