Sub topic 3
How resample() groups rows into bins
This chapter explains what happens inside resample() between the call and the result. Once you can see the binning step, the aggregation and fill options in later chapters are easier to predict.
It assumes you know basic Python, how to build and select from a pandas Series or DataFrame, and what a DatetimeIndex is. Frequency strings such as "D", "W" and "MS" were covered in the previous chapter. This chapter only uses them.
The core idea: a groupby over time
resample() works like groupby(), except the groups are time intervals instead of distinct values. It builds a regular grid of time intervals called bins, assigns each row to the bin that contains its timestamp, and then reduces each bin to one row.
Here is the first example, which turns daily values into weekly sums.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=10, freq="D")
s = pd.Series(range(10), index=idx)
weekly = s.resample("W").sum()
print(weekly)The output is:
2024-01-07 21
2024-01-14 24
Freq: W-SUN, dtype: int64"W" means weeks ending on Sunday. 2024-01-01 is a Monday, so the first bin holds January 1 to 7, with values 0 through 6, which sum to 21. The second bin holds January 8 to 10, with values 7, 8 and 9, which sum to 24. That second bin is only partly filled, but it still appears in the result.
Three steps inside resample()
Every resample follows the same three steps.
- Build the bin edges. pandas takes the first and last timestamps in the index, expands them outward to fit the frequency, and generates a regular sequence of edges between them.
- Assign rows to bins. Each timestamp is compared with the edges and placed in exactly one bin.
- Reduce each bin. The aggregation you choose (
sum,meanand so on) runs on the rows in each bin and produces one value per bin.
The Resampler object is lazy
s.resample("W") does not compute anything useful on its own. It returns a Resampler object, which stores the settings (frequency, closed, label, and so on) and waits for you to call a method on it.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=10, freq="D")
s = pd.Series(range(10), index=idx)
r = s.resample("W")
print(type(r).__name__)
print(r.size())
print(r.sum())r.size() returns the number of rows in each bin, which is 7 and 3 here. It is a quick way to check how pandas split your data before you aggregate. You can reuse r for several aggregations, for example r.sum() and then r.mean().
Bin edges depend on the frequency
How pandas places the edges depends on the kind of frequency you pass.
- Calendar frequencies such as
"W","MS"and"YS"anchor to the calendar. Weekly bins end on Sunday, and"MS"bins start on the first of each month. The edges do not depend on where your data starts. - Fixed-length frequencies such as
"D","h","15min"and"3D"have a constant length. Their edges are measured from an origin. By default the origin is midnight of the first day in your data (origin="start_day").
The fixed-length case matters when the multiple is greater than 1. This example uses 3-day bins on ten days of data.
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("3D").sum())The result has four bins, labeled 2024-01-01, 2024-01-04, 2024-01-07 and 2024-01-10. Their sums are 3, 12, 21 and 9. The bins start on the first day of your data, so if your data started on January 2 the edges would shift by one day. A later chapter covers origin and offset, which let you move the grid on purpose.
Which side of the bin includes the edge
A timestamp that lands exactly on an edge has to go into one of the two neighboring bins. Two parameters decide this:
closedsays which end of each bin includes its edge ("left"or"right").labelsays which edge becomes the bin's label in the result.
The defaults are "left" for both, with an exception: the end-anchored frequencies ("W", "ME", "QE", "YE" and their business variants) default to "right" for both. That is why the weekly result above is labeled with the Sunday that ends each week, and why a row stamped exactly Sunday at midnight belongs to the week that ends on that Sunday.
The result index is a full regular grid
The result of a resample always has an evenly spaced index from the first bin to the last bin. If some bins in the middle have no rows, they still appear. Bins are generated from the edges, not from the data.
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-08", "2024-01-25"])
s = pd.Series([1, 2, 3, 4], index=idx)
print(s.resample("W").sum())
print(s.resample("W").size())The data skips the weeks ending January 14 and January 21. The result still has a row for each of those weeks, and size() shows 0 for them. A bin with no rows is not an error. Chapter 9 explains why sum() gives 0 for such a bin while mean() gives NaN.
This is the main practical difference from groupby. A groupby on the week number would silently omit the empty weeks, while resample keeps the timeline continuous.
Resampler methods fall into two groups
Once you hold a Resampler, the methods you call decide what happens to each bin.
| Kind | Examples | Used when |
|---|---|---|
| Aggregations | `sum`, `mean`, `min`, `max`, `count`, `first`, `last`, `ohlc`, `agg` | Going to a coarser frequency (downsampling), where many rows become one |
| Fill methods | `ffill`, `bfill`, `interpolate`, `asfreq`, `nearest` | Going to a finer frequency (upsampling), where some bins have no rows |
You can call either kind regardless of direction. Using mean() on an upsampled series gives NaN for the new rows, because each new bin has no rows to average. Later chapters cover the sensible pairings.
Common errors
The index is not a datetime. resample() requires a DatetimeIndex, PeriodIndex or TimedeltaIndex. A plain integer index, or a column of date strings, raises a TypeError.
import pandas as pd
df = pd.DataFrame({"date": ["2024-01-01", "2024-01-02"], "x": [1, 2]})
try:
df.resample("D").sum()
except TypeError as exc:
print("TypeError:", exc)
fixed = df.assign(date=pd.to_datetime(df["date"])).set_index("date")
print(fixed.resample("D").sum())The fix is to convert with pd.to_datetime() and then call set_index(). If you would rather keep the column as a column, on= also works, as a later chapter shows.
Expecting bins to start at the first row. For calendar frequencies, the first bin is aligned to the calendar. The first label may be earlier or later than your first timestamp. For "W" the first label is the first Sunday on or after your first timestamp.
Forgetting the aggregation. s.resample("W") alone prints a Resampler object, not data. If you see something like DatetimeIndexResampler [freq=<Week: weekday=6>, ...], you still need to add .sum() or another method.
Reading the labels as exact dates. A monthly or weekly label is one edge of an interval, so check it against closed and label before joining the result with other data.
Summary of the working model
resample(rule)builds a regular grid of bins and returns a lazyResampler.- Each row goes to exactly one bin, decided by the edges,
closed, and, for fixed-length rules, the origin. - An aggregation reduces each bin to one row. The result index holds one label per bin, including empty bins.
size()on theResampleris a cheap way to inspect the binning.
Exercise
A Series has a daily DatetimeIndex from 2024-01-01 for 10 days, with values 0 through 9. You call s.resample("3D").sum(). What are the index labels of the result and the sum in the last bin, and why is the last bin smaller than the others?
Show answer
The labels are 2024-01-01, 2024-01-04, 2024-01-07 and 2024-01-10. The last bin holds only the row for January 10 (value 9), so its sum is 9. Fixed-length bins like "3D" start at midnight of the first day and each cover three days. Ten days divide into three full bins and one bin with only one row left over, and pandas still returns that partial bin.
Exercise
A Series has observations on 2024-01-01, 2024-01-02, 2024-01-08 and 2024-01-25. You run s.resample("W").size(). Does the result have rows for the weeks ending 2024-01-14 and 2024-01-21, and what values do they have?
Show answer
Yes. resample() builds bins from the edges, not from the data, so the result is a continuous weekly index from the week ending 2024-01-07 to the week ending 2024-01-28. The weeks ending January 14 and January 21 contain no observations, so size() reports 0 for both.