Sub topic 10
Resampling on a column instead of the index
This chapter assumes you can build a DataFrame, select columns, and know what resample() does with a DatetimeIndex. Earlier chapters covered frequency strings, bins, and aggregation.
Why use `on=`
Real data often arrives with dates in an ordinary column and a default integer index. You could call set_index("date") first. The on= argument skips that step and keeps the DataFrame as it is.
import pandas as pd
df = pd.DataFrame(
{
"date": pd.to_datetime(["2024-01-05", "2024-01-20", "2024-03-02"]),
"sales": [100, 150, 80],
}
)
monthly = df.resample("MS", on="date")["sales"].sum()
print(monthly)The output is:
date
2024-01-01 250
2024-02-01 0
2024-03-01 80
Freq: MS, Name: sales, dtype: int64Three things to notice:
- The result is indexed by the bin labels, which are month starts, not by the original row labels.
- The index is named
date, taken from the column you passed. - The
datecolumn is not aggregated. It is used only to assign rows to bins.
The column must be datetime-like
on= accepts a column of dtype datetime64. If the column holds strings, pandas raises a TypeError saying resample is only valid with a DatetimeIndex, TimedeltaIndex or PeriodIndex. Convert first with pd.to_datetime().
df["date"] = pd.to_datetime(df["date"])Empty bins
February has no rows, so its bin is empty. For sum(), an empty bin gives 0 by default. That can mislead: zero sales and unknown sales look the same. Pass min_count=1 to require at least one value in the bin, otherwise the result is NaN.
sparse = df.resample("MS", on="date")["sales"].sum(min_count=1)
print(sparse)The output is:
date
2024-01-01 250.0
2024-02-01 NaN
2024-03-01 80.0
Freq: MS, Name: sales, dtype: float64The dtype changed from integer to float because NaN cannot be stored in an integer column. Methods such as mean() already return NaN for empty bins, so min_count matters mainly for sum() and prod().
Equivalent forms
These two lines give the same numbers:
a = df.resample("MS", on="date")["sales"].sum()
b = df.set_index("date")["sales"].resample("MS").sum()Use on= when you want to keep the DataFrame unchanged and only need one aggregation. Use set_index() when you will do several time-based operations, such as slicing by date strings, since those need the index.
Resampling on an index level
If your dates are one level of a MultiIndex, use level= instead of on=. Pass the level name or position. The other levels are dropped from the result, so combining several groups needs a groupby, which a later chapter covers.
Common errors
- Passing a string column without converting it, which raises a
TypeError. - Using both
on=and aDatetimeIndexand expecting the index to win. Whenon=is given, the column is used. - Reading a
0in a sparse month as real data. Usemin_count=1when absence matters.
Exercise
A DataFrame df has a ts column of dtype datetime64 and a numeric units column. Write one line that gives weekly totals of units, with weeks that have no rows shown as NaN instead of 0.
Show answer
df.resample("W", on="ts")["units"].sum(min_count=1)