Sub topic 10
Resampling to regular intervals
This chapter assumes you can build a Series or DataFrame with a DatetimeIndex, and that you know the .dt accessor and the frequency aliases from date_range. You also need to be comfortable with aggregations such as sum and mean. Everything here uses pandas 2.2 or later, where hourly is "h" and month end is "ME".
What resampling does
Raw time data rarely arrives on a tidy schedule. Sensor readings, sales and log events show up whenever they happen. Resampling regroups those rows into regular intervals, called bins, and reduces each bin to one value.
resample works like groupby, but the groups are time bins. The method returns a Resampler object, and nothing is computed until you call an aggregation on it.
There are two directions:
- Downsampling moves to a coarser frequency, such as minutes to hours. You must choose how to combine the rows in each bin.
- Upsampling moves to a finer frequency, such as weeks to days. The new rows have no data, so you choose how to fill them.
The diagram shows the downsampling path for irregular events.
Downsampling with an aggregation
Start with a regular daily series and aggregate it to weeks.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=10, freq="D")
s = pd.Series(range(10), index=idx)
print(s.resample("W").sum())The output is:
2024-01-07 21
2024-01-14 24
Freq: W-SUN, dtype: int64The "W" alias means weeks ending on Sunday. January 1, 2024 is a Monday. The first bin therefore covers January 1 to 7 and sums 0 through 6, which gives 21. The second bin is only partly filled, because the data stops on January 10. pandas still reports it, so a trailing partial period looks like a full one. Check the last bin before you trust it.
Irregular data works the same way. Here five events fall into two hours of the day.
import pandas as pd
events = pd.Series(
[5, 3, 8, 2, 7],
index=pd.to_datetime([
"2024-03-01 09:05",
"2024-03-01 09:20",
"2024-03-01 09:50",
"2024-03-01 11:10",
"2024-03-01 11:40",
]),
)
hourly = events.resample("h").sum()
print(hourly)This prints three rows: 16 at 09:00, 0 at 10:00 and 9 at 11:00. The 10:00 row exists even though no event happened then. Resampling creates every bin between the first and last timestamp, whether or not it holds data. This is the main reason to resample: the result has a complete, evenly spaced axis.
Empty bins and aggregation choice
An empty bin does not behave the same way under every aggregation.
| Aggregation | Result for an empty bin |
|---|---|
| `sum()` | 0 |
| `count()` | 0 |
| `mean()`, `min()`, `max()` | NaN |
| `first()`, `last()` | NaN |
A zero from sum() can be misleading. "No events" and "the sensor was offline" both produce 0. If that difference matters, pass min_count=1, so that events.resample("h").sum(min_count=1) returns NaN for the empty bin.
You can apply several aggregations at once with agg.
stats = events.resample("h").agg(["sum", "mean", "count"])
print(stats)For price data, ohlc() returns the open, high, low and close of each bin as four columns.
prices = pd.Series(
[10.0, 10.5, 10.2, 11.0, 10.8],
index=pd.to_datetime([
"2024-03-01 09:01",
"2024-03-01 09:10",
"2024-03-01 09:40",
"2024-03-01 10:05",
"2024-03-01 10:50",
]),
)
print(prices.resample("h").ohlc())Resampling a column instead of the index
Your timestamps are often in a column, not the index. Use on= so you do not have to call set_index first.
import pandas as pd
df = pd.DataFrame({
"when": pd.to_datetime(["2024-03-01 09:30", "2024-03-02 14:45", "2024-03-05 08:00"]),
"amount": [10, 25, 40],
})
daily = df.resample("D", on="when")["amount"].sum()
print(daily)The result has five rows, from March 1 to March 5. March 3 and March 4 appear with a total of 0. If you want only days that have data, use groupby(df["when"].dt.date) instead. That groups by the dates that exist and creates no empty bins.
If neither the index nor the on= column is datetime-like, pandas raises a TypeError saying it only works with DatetimeIndex, TimedeltaIndex or PeriodIndex. The usual cause is a column that is still text, so convert it with pd.to_datetime first.
Upsampling and filling gaps
Going from a coarse to a fine frequency creates rows with no data. The Resampler offers several ways to fill them.
import pandas as pd
weekly = pd.Series(
[100, 110, 120],
index=pd.date_range("2024-01-01", periods=3, freq="7D"),
)
print(weekly.resample("D").asfreq()) # new rows are NaN
print(weekly.resample("D").ffill()) # carry the last value forward
print(weekly.resample("D").interpolate()) # straight line between known pointsEach method answers a different question:
asfreq()only inserts the new timestamps. Original values stay and the rest are NaN.ffill()repeats the last known value. It suits stepwise quantities, such as a price that holds until it changes.interpolate()draws a line between known values. It suits smoothly varying quantities, such as temperature.
Interpolating a count, such as units sold, produces fractional values that never happened. Choose the fill method from what the number means.
Bin edges: closed, label, origin and offset
Two settings decide which bin a timestamp falls into and what the bin is called.
closedsays which end of the interval includes its boundary:"left"for[start, end)or"right"for(start, end].labelsays which edge names the bin.
For most frequencies both default to "left". The exceptions are the end-anchored aliases "W", "ME", "QE" and "YE", which default to "right". That is why the weekly example above was labeled January 7, the last day of the week, and not January 1.
You can override both.
s = pd.Series(range(10), index=pd.date_range("2024-01-01", periods=10, freq="D"))
print(s.resample("W", closed="left", label="left").sum())The result is 15 for 2023-12-31 and 30 for 2024-01-07. The bins are now [Sunday, next Sunday), so January 7 moves into the second bin and the totals change. Both results add up to 45, which is the sum of all ten values. Only the grouping differs.
For fixed-length frequencies, such as "15min", "2h" or "1D", bins start from the midnight of the first day by default (origin="start_day"). To shift the boundaries, use offset. For example, to make a "day" run from 06:00 to 06:00:
shifted = s.resample("1D", offset="6h").sum()Use origin="start" to align bins to the first timestamp of the data. Without that, a series starting at 09:07 with "30min" bins is still cut at 09:00 and 09:30.
Time zones and daylight saving
On a time-zone-aware index, daily bins follow local midnight. On a day when clocks change, the local day is 23 or 25 hours long. Resampling a localized series with "D" gives one bin per local day, and hourly counts inside a 23-hour day will be lower than usual. Localize the data first, then resample.
A series that mixes time zones cannot be resampled. Convert everything to one zone first.
Resampling versus rolling
resample changes the number of rows and returns one row per bin. rolling("3D") keeps one row per original timestamp and looks back over a window. Use resample to build a regular axis. Use rolling to smooth values on an axis you already have. The two combine well: resample to daily totals, then take a rolling mean of those totals.
Common mistakes
- Using the old aliases.
"M"and"H"are deprecated, so use"ME"and"h". Older tutorials still show the old forms. - Reading weekly or monthly labels as start dates. With the right-labeled defaults they are end dates.
- Treating a trailing partial bin as a complete period.
- Taking a 0 from
sum()to mean "nothing was measured". - Calling
resampleon text timestamps, or on data withNaTin the index. Convert and clean the index first.
Exercise
A DataFrame sales has a datetime column when and a numeric column amount. Write one expression that returns the average amount per calendar month, labeled by the month end, with months that have no rows showing NaN.
Show answer
sales.resample("ME", on="when")["amount"].mean(). The "ME" alias creates month-end bins labeled by the last day of the month. on="when" uses the column as the time axis. mean() returns NaN for any month with no rows.
Exercise
You resample hourly sensor counts to a daily series with resample("D").sum() and a day shows 0. Give two possible meanings of that 0, and say how you would tell them apart.
Show answer
The sensor may have recorded zero events, or it may have been offline and recorded nothing, because sum() returns 0 for an empty bin. To tell them apart, run resample("D").count() on the same data. A count of 0 means no rows existed in that bin. A positive count with a sum of 0 means rows existed and their values were 0. Alternatively, use sum(min_count=1) so empty bins become NaN.