Sub topic 1
Start with a DatetimeIndex
Every resample() call depends on one fact: pandas must know which row happened when. This chapter covers how to give it that information and how to check that you did. It also covers the mistakes that most often break the later steps in this tutorial.
Prerequisites
This chapter assumes you can:
- Write basic Python: variables, function calls, and
try/except. - Create and inspect a pandas
SeriesandDataFrame. - Select data with
.locand set or reset an index. - Read a date such as
2024-03-02and know that02/03/2024can mean two different days.
You need pandas 2.0 or later. The examples also work on recent 1.x releases, apart from small differences in printed output.
Why resample() needs a time-aware index
resample() groups rows into time bins, such as one bin per week. To do that, it reads the row labels and decides which bin each label belongs to. Only three index types carry that meaning:
| Index type | What it holds | Works with resample() |
|---|---|---|
| `DatetimeIndex` | Specific moments, such as `2024-01-05 09:30` | Yes |
| `PeriodIndex` | Spans of time, such as "January 2024" | Yes |
| `TimedeltaIndex` | Durations, such as 90 minutes | Yes |
| `RangeIndex`, `Index` of strings or integers | Plain labels | No |
This tutorial uses DatetimeIndex almost everywhere. The last chapters cover PeriodIndex separately.
A column that looks like a date is not enough. A column of strings such as "2024-01-05" is still text, and pandas will not guess. The following code shows the failure.
import pandas as pd
df = pd.DataFrame(
{
"date": ["2024-01-05", "2024-01-20", "2024-03-02"],
"sales": [100, 150, 80],
}
)
try:
df.resample("MS").sum()
except TypeError as err:
print(err)The message reads: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'. The error names the index, not the column. The fix is to change what the index is.
Building a DatetimeIndex
There are two common situations. In the first, you create the timestamps yourself. In the second, you already have a column of dates.
Generating timestamps with date_range
pd.date_range() builds a regular sequence. You give it a start and either an end or a number of periods, plus a frequency string. Frequency strings are the subject of the next chapter. Here "D" means one calendar day.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=5, freq="D")
s = pd.Series([3, 5, 2, 8, 6], index=idx)
print(type(s.index).__name__)
print(s.index.freq)
print(s)The index type is DatetimeIndex. Its freq attribute is <Day>, which means pandas knows the spacing is exactly one day.
Converting a column with to_datetime and set_index
Most real data arrives as text. The usual steps are to parse the column, then move it into the index.
import pandas as pd
df = pd.DataFrame(
{
"date": ["2024-01-05", "2024-01-20", "2024-03-02"],
"sales": [100, 150, 80],
}
)
df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date")
print(df.index)
print(df.resample("MS").sum())The result has three rows: January with 250, February with 0, and March with 80. February had no input rows, but resample() still produced a bin for it. Chapter 9 covers that behavior.
You can also parse while loading. pd.read_csv("sales.csv", parse_dates=["date"], index_col="date") does both steps in one call.
Parsing dates safely
to_datetime is forgiving by default, and that can hide mistakes. Three habits prevent most problems.
- Pass
format=when you know the layout. Without it, pandas infers the format from the first values. A string like03/04/2024is read as month first unless you say otherwise. Withformat="%d/%m/%Y", it is always day first. - Use
errors="coerce"to find bad values. Unparseable strings becomeNaT("not a time"), the datetime version ofNaN. You can then count them and decide what to do. - Remove
NaTbefore setting the index. A row with no timestamp has no bin to belong to.
import pandas as pd
raw = pd.Series(["03/04/2024", "15/04/2024", "not a date"])
parsed = pd.to_datetime(raw, format="%d/%m/%Y", errors="coerce")
print(parsed)
print("bad values:", parsed.isna().sum())
clean = pd.Series([1, 2, 3], index=parsed).dropna(how="all")
clean = clean[clean.index.notna()]
print(clean)The first two strings become April 3 and April 15. The third becomes NaT. The last filter keeps only the rows whose index is a real timestamp.
Checking the index before you resample
Three properties of the index affect the results. None of them prevents resample() from running, so you must check them yourself.
Order
resample() sorts the data internally, so unsorted input still produces correct bins. Other operations are stricter. For example, slicing a range of dates with .loc["2024-01":"2024-02"] expects a sorted index. Call df.sort_index() right after you build the index, and you will not have to think about it again.
Duplicates
Duplicate timestamps are allowed. Two rows stamped 2024-01-05 10:00 land in the same bin, and the aggregation combines them. That is correct for transaction logs, where two sales can occur in the same second. It is a bug if the duplicates come from a data export that repeated rows. Check with df.index.duplicated().sum().
Regularity and the freq attribute
An index built by date_range has a freq value. An index built from parsed data usually shows freq=None, even when the spacing looks regular. resample() does not need freq. It works from the actual timestamps. The freq value matters for a few other methods, and you can look at it to see whether pandas considers the series regular.
import pandas as pd
idx = pd.to_datetime(["2024-01-03", "2024-01-01", "2024-01-01", "2024-01-02"])
s = pd.Series([4, 1, 2, 3], index=idx)
print("sorted:", s.index.is_monotonic_increasing)
print("duplicates:", s.index.duplicated().sum())
print("freq:", s.index.freq)
s = s.sort_index()
print(s.resample("D").sum())The index is out of order, has one duplicate, and has no freq. The resample still works. The two values stamped January 1 are summed to 3, so the daily totals are 3, 3, and 4.
Time zones in the index
A DatetimeIndex is either time-zone-naive or time-zone-aware. A naive index holds clock readings with no zone attached. An aware index holds moments tied to a zone, such as 2024-03-10 09:00-05:00.
If your source data mixes UTC offsets in one column, to_datetime cannot make a single zone-aware dtype out of it. You get a column of Python objects, and set_index on that column will not give you a DatetimeIndex. Pass utc=True to convert everything to UTC first. You can then use tz_convert to move to a local zone.
import pandas as pd
mixed = ["2024-03-10 09:00:00-05:00", "2024-03-10 15:00:00+01:00"]
stamps = pd.to_datetime(mixed, utc=True)
print(stamps.tz)
print(stamps.tz_convert("America/New_York"))Resampling in a zone that has daylight saving time changes bin lengths on the transition days. A "day" can be 23 or 25 hours long. Chapter 14 covers that. For now, decide on one zone early and keep it consistent.
From raw data to a resample-ready index
The following diagram shows the whole path, including the checks that catch the common failures.
Common errors
TypeError: Only valid with DatetimeIndex...: The index is aRangeIndexor holds strings. Convert the date column and callset_index. If you would rather keep the column where it is,resample("MS", on="date")also works. Chapter 10 covers that option.- Dates read in the wrong order: Day and month were swapped by inference. Pass
format=. - A column of strings after
to_datetime: Checkdf["date"].dtype. A result ofobjectmeans parsing did not produce real timestamps. Look for mixed offsets or unparseable entries, and useutc=Trueorerrors="coerce". - Bins that seem to skip rows: Rows with
NaTin the index are dropped from the groups. CountNaTvalues first. - Wrong column resampled: After
set_index("date"), thedatecolumn is no longer indf.columns. It is the index. Usereset_index()if you need it back as a column.
Exercise
A DataFrame has a column ts of strings in day-first form, such as "25/12/2024", plus a numeric column amount. Write the steps to get monthly totals of amount, and name one check that would catch a day/month swap.
Show answer
Parse with an explicit format, move the result into the index, sort, then resample: df["ts"] = pd.to_datetime(df["ts"], format="%d/%m/%Y"), df = df.set_index("ts").sort_index(), df["amount"].resample("MS").sum(). To catch a swap, check that df.index.min() and df.index.max() fall in the date range you expect, or that no month number above 12 was misread. Passing format= prevents the swap in the first place.
Exercise
Your index shows freq=None and contains two rows with the same timestamp. Will resample("D").sum() fail? What happens to the duplicate rows?
Show answer
It will not fail. resample() works from the actual timestamps, so a missing freq does not matter. The two rows fall in the same daily bin, and sum() adds their values together. Whether that is correct depends on whether the duplicates are real events or repeated export rows.