Sub topic 10
Resampling on a column instead of the index
This chapter assumes you can build a DataFrame, select columns, and call resample() on a Series with a DatetimeIndex. It also assumes you know frequency strings such as "W" and "MS". Real data often arrives with dates in an ordinary column and a default integer index. You can resample it without restructuring it first.
The problem: dates that are not in the index
resample() bins rows by their timestamps. By default it reads the timestamps from the index, so it needs a DatetimeIndex, TimedeltaIndex, or PeriodIndex. A table loaded from a CSV file usually has a RangeIndex and a separate date column. Calling resample() on it directly fails.
import pandas as pd
df = pd.DataFrame(
{
"date": pd.to_datetime(["2024-01-05", "2024-01-20", "2024-03-02"]),
"sales": [100, 150, 80],
}
)
try:
df.resample("MS").sum()
except TypeError as err:
print("TypeError:", err)The message begins with "Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex". It then names the index type it received, here RangeIndex. There are two fixes. You can move the column into the index with set_index("date"), or you can tell resample() which column to use.
Using on=
The on parameter names a column to use as the time axis. The index stays untouched.
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)
sparse = df.resample("MS", on="date")["sales"].sum(min_count=1)
print(sparse)The first call prints:
date
2024-01-01 250
2024-02-01 0
2024-03-01 80
Freq: MS, Name: sales, dtype: int64The second call gives NaN for February, and the dtype becomes float64:
date
2024-01-01 250.0
2024-02-01 NaN
2024-03-01 80.0
Freq: MS, Name: sales, dtype: float64Four details of this behavior matter in practice:
- The result is indexed by the date column. The new index carries the column's name,
date. Callreset_index()if you want the dates back as a regular column. - The
oncolumn is not aggregated. It becomes the index of the result, so you do not see it among the aggregated columns. - February still appears.
resample()builds a complete grid of bins from the first to the last timestamp. A bin with no rows is empty. An empty bin sums to0by default, or toNaNwhen you passmin_count=1. The chapter on empty bins covers this choice in more detail. - Rows with
NaTare skipped. A missing timestamp cannot be placed in any bin, so that row contributes nothing.
The column must be datetime-like
on= requires a column with a datetime dtype. A column of strings does not work, even if the strings look like dates. This is the most common error with on=. Convert the column with pd.to_datetime() first.
import pandas as pd
raw = pd.DataFrame(
{
"date": ["2024-01-05", "2024-01-20", "2024-03-02"],
"sales": [100, 150, 80],
}
)
try:
raw.resample("MS", on="date")["sales"].sum()
except TypeError as err:
print("Before conversion:", type(err).__name__)
raw["date"] = pd.to_datetime(raw["date"])
print(raw.resample("MS", on="date")["sales"].sum())The first attempt raises TypeError, because the column has dtype object. After conversion the call succeeds and prints the same monthly totals as before.
on= versus set_index
For a single call, on= and set_index() give the same numbers. You can check that.
import pandas as pd
df = pd.DataFrame(
{
"date": pd.to_datetime(["2024-01-05", "2024-01-20", "2024-03-02"]),
"sales": [100, 150, 80],
}
)
a = df.resample("MS", on="date")["sales"].sum()
b = df.set_index("date").resample("MS")["sales"].sum()
print(a.equals(b))This prints True. The choice between them is about workflow:
| Approach | Best when | Trade-off |
|---|---|---|
| `resample(on="date")` | You need one or two resampled views and want to keep the original layout | The index is not a time index, so `df.loc["2024-01"]` slicing does not work on the original |
| `set_index("date")` first | You will slice by date, resample repeatedly, or call other time-aware methods | You must call `reset_index()` if you want the column back |
| `resample(level="date")` | The time axis is one level of a MultiIndex | Other index levels are combined, as described below |
Aggregating several columns after on=
When the DataFrame has more than one value column, apply the aggregation to the Resampler object. Named aggregation gives you readable column names. Each keyword is a new output column, and each value is a pair of an input column and an aggregation.
import pandas as pd
df = pd.DataFrame(
{
"order_date": pd.to_datetime(
["2024-01-03", "2024-01-17", "2024-02-05", "2024-02-06", "2024-02-20"]
),
"customer": ["a", "b", "a", "c", "b"],
"amount": [120.0, 80.0, 50.0, 200.0, 25.0],
}
)
summary = df.resample("MS", on="order_date").agg(
orders=("customer", "count"),
revenue=("amount", "sum"),
largest=("amount", "max"),
)
print(summary)The output is:
orders revenue largest
order_date
2024-01-01 2 200.0 120.0
2024-02-01 3 275.0 200.0The customer column is text, so only count makes sense for it. If you call a bare .sum() or .mean() on the whole Resampler, pandas applies it to every remaining column. For text columns, sum() concatenates strings and mean() raises an error. Select the columns you want before aggregating, or use named aggregation as above.
Using level= with a MultiIndex
Sometimes the timestamps are one level of a MultiIndex. In that case, pass the level's name or position to level=. The level must hold datetime values.
import pandas as pd
idx = pd.MultiIndex.from_product(
[["A", "B"], pd.date_range("2024-01-01", periods=4, freq="D")],
names=["store", "day"],
)
s = pd.Series(range(8), index=idx)
print(s.resample("2D", level="day").sum())Store A holds the values 0 to 3 and store B holds 4 to 7. The first two-day bin adds 0 + 1 + 4 + 5, and the second adds 2 + 3 + 6 + 7:
day
2024-01-01 10
2024-01-03 18
Freq: 2D, dtype: int64The store level disappears, because level= bins on time alone and merges the other levels. If you want one result per store, you need a grouped resample, which a later chapter covers.
Choosing between the options
Other options still apply
on= changes only where the timestamps come from. Everything else about binning behaves as it does for an index. You can still pass closed, label, origin, and offset. Downsampling, aggregation, and empty-bin rules are the same. Upsampling is the one case to be careful with. Methods such as ffill() and interpolate() work on the result of resampling, which is indexed by the new grid, so the original row order in the DataFrame is not preserved.
Because the result is indexed by the date column, it is often followed by reset_index() before merging or plotting.
import pandas as pd
df = pd.DataFrame(
{
"date": pd.to_datetime(["2024-01-05", "2024-01-20", "2024-03-02"]),
"sales": [100, 150, 80],
}
)
flat = df.resample("MS", on="date")["sales"].sum().reset_index()
print(flat)This prints a regular DataFrame with a date column and a sales column, and a fresh integer index of 0, 1, 2.
Common errors
TypeError: Only valid with DatetimeIndex...: either you forgoton=, or the column is not datetime dtype. Checkdf.dtypes.KeyErrorfor the column name: afterset_index("date"),dateis no longer a column, soon="date"fails. Use one approach or the other.- Unexpected zeros in empty periods: the default
sum()returns0for empty bins. Usesum(min_count=1)when a missing period should stay missing. - Mixed time zones in the column: a column with mixed UTC offsets becomes
objectdtype and cannot be used withon=. Convert withpd.to_datetime(..., utc=True)first.
Exercise
A DataFrame orders has columns placed (strings such as "2024-05-14") and total (numbers), with a default integer index. Write the code that gives weekly totals of total, with empty weeks showing NaN instead of 0.
Show answer
Convert the column first, then resample on it and use mincount=1:
orders["placed"] = pd.todatetime(orders["placed"])
weekly = orders.resample("W", on="placed")["total"].sum(mincount=1)
The conversion is needed because on= rejects string columns. `mincount=1` makes any bin with no rows return NaN instead of the default 0.
Exercise
You call df.set_index("date").resample("MS", on="date"). What happens, and what is the fix?
Show answer
It fails, because date is no longer a column after set_index, and on= looks for a column. Either drop on="date" and call df.set_index("date").resample("MS"), or skip set_index and call df.resample("MS", on="date").