Sub topic 10
Resampling to regular intervals
This chapter assumes you can build a Series with a DatetimeIndex and select rows by date, as covered in the indexing chapter. You should also know groupby-style aggregation such as sum and mean.
What resampling does
Real data rarely arrives on a clean schedule. Sensor readings, sales and log events land at irregular moments. Resampling changes the series to a regular interval, such as hourly, daily or monthly. It works like groupby, except the groups are time bins computed from the index.
resample needs a DatetimeIndex (or a PeriodIndex, or on="column" for a datetime column). It returns a lazy object. Nothing is computed until you call an aggregation on it.
Downsampling
Downsampling moves to a coarser interval, so many rows collapse into one. The next example reuses a daily series and sums it by week.
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 has two rows: 21 for the bin labeled 2024-01-07 (values 0 to 6) and 24 for the bin labeled 2024-01-14 (values 7 to 9). The alias "W" means weeks ending on Sunday. January 1, 2024 is a Monday, so the first bin is a full week and the second is partial.
Irregular data and empty bins
Resampling also regularizes uneven timestamps. Bins that contain no rows still appear in the result.
import pandas as pd
idx = pd.to_datetime([
"2024-03-01 09:30",
"2024-03-01 09:50",
"2024-03-01 11:10",
"2024-03-02 08:00",
])
readings = pd.Series([10, 20, 5, 40], index=idx)
print(readings.resample("12h").sum())The result has three rows: 35 at 2024-03-01 00:00, 0 at 2024-03-01 12:00 and 40 at 2024-03-02 00:00. The middle bin has no data, so sum reports 0. A mean over the same bin gives NaN, because there is nothing to average. Choose the aggregation with this in mind. A sum of "nothing" is 0, which can hide a gap that you would want to see as missing.
You can request several statistics at once:
print(readings.resample("D").agg(["sum", "mean", "count"]))Checking count is a quick way to find bins that are empty or thin.
Upsampling
Upsampling moves to a finer interval than the data. The new rows have no values, so you decide how to fill them.
hourly = readings.resample("h").asfreq()
filled = readings.resample("h").ffill()asfreq() keeps original values and leaves NaN elsewhere. ffill() carries the last known value forward. Use ffill only when the value really persists, such as a price or a setting. Do not use it for counts or amounts that happen at a moment.
Bin edges and labels
Each bin has a left and right edge, and one of them is included. The closed argument chooses which, and label chooses which edge names the bin.
- For most aliases, bins are left-closed and left-labeled. A row at 09:30 falls in the bin labeled 09:00 when resampling hourly.
- For period-end aliases (
"W","ME","QE","YE"), bins are right-closed and right-labeled. The label is the last day of the span.
You can override either default:
print(s.resample("W", closed="left", label="left").sum())If your totals are off by one bin, check these two arguments first.
Resample versus rolling
Resampling produces one row per bin, and the bins do not overlap. A time-based rolling window such as s.rolling("3D").mean() produces one row per original timestamp. Each result looks back over the trailing three days, so windows overlap. Use resample to change the interval of the data. Use rolling to smooth data while keeping its timestamps.
Common mistakes
- Calling
resampleon a column withouton="col", or on an unsorted or non-datetime index. This raises aTypeError. - Reading a
0from an empty bin as real data. - Forgetting that
"W"ends on Sunday, so weeks do not start on Monday.
Exercise
A DataFrame df has a datetime index and a column sales. You want total sales per calendar month, labeled by the last day of each month. What expression do you write, and what do you get for a month with no rows?
Show answer
Use df["sales"].resample("ME").sum(). Month-end bins are right-labeled, so each label is the month's last day. A month with no rows still appears, and sum gives 0 for it. If you want it shown as missing, use .sum(min_count=1), which returns NaN for empty bins.