Sub topic 5
Choosing aggregations, including ohlc and per-column agg
This chapter assumes you can build a DatetimeIndex, write frequency strings such as "2D" or "MS", and call resample(...) on a Series or DataFrame. Once rows are grouped into bins, you choose how each bin collapses into one value. That choice decides whether the result is correct.
What the Resampler offers
resample() returns a Resampler object. It holds the bins and does no computation until you call a method on it. Common choices are:
| Method | Result per bin | Typical use |
|---|---|---|
| `sum()` | Total of the values | Sales, traffic, rainfall |
| `mean()`, `median()` | Average, middle value | Temperature, price level |
| `min()`, `max()` | Smallest, largest | Daily low and high |
| `first()`, `last()` | First or last non-null value | Opening or closing balance |
| `count()` | Number of non-null values | Data quality checks |
| `size()` | Number of rows, nulls included | Row counts |
| `std()`, `var()` | Spread | Volatility |
| `nunique()` | Distinct values | Unique users per day |
| `ohlc()` | Open, high, low, close | Price series |
| `agg()` | Any combination of the above | Mixed columns |
Match the aggregation to what the number means
First decide what the value measures. A flow, such as units sold, adds up across a period, so use sum(). A level, such as temperature or a price, describes a moment, so use mean(), last(), or ohlc(). A stock, such as an account balance, should be read at a point in time, usually with last().
The wrong choice runs without error and returns plausible numbers. Summing daily temperatures gives a meaningless total. Averaging daily sales gives the average day, not the weekly total.
Aggregating a single column
Calling a method on a Series resampler returns a Series. Calling it on a DataFrame resampler applies the method to every column.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
df = pd.DataFrame(
{
"price": [10, 12, 11, 15, 14, 13],
"volume": [100, 200, 150, 50, 300, 100],
},
index=idx,
)
print(df.resample("2D").sum())Here sum() is right for volume but wrong for price. A DataFrame-wide call gives one rule to every column, which is why you need agg().
ohlc: four statistics in one call
ohlc() returns the first value (open), the maximum (high), the minimum (low), and the last value (close) of each bin. Financial charts use it, but it also summarizes any level that you want to see as a range, such as a sensor reading.
import pandas as pd
idx = pd.date_range("2024-01-01 09:00", periods=6, freq="min")
ticks = pd.Series([100, 102, 99, 101, 105, 103], index=idx)
print(ticks.resample("3min").ohlc()) open high low close
2024-01-01 09:00:00 100 102 99 99
2024-01-01 09:03:00 101 105 101 103On a Series, the result has four columns. On a DataFrame, ohlc() runs for every column and produces MultiIndex columns such as ("price", "open"). Select the column first to keep the result flat:
print(df["price"].resample("2D").ohlc())open and close depend on row order within the bin. Sort the index first with sort_index() if your data might arrive out of order.
Different aggregations for different columns
agg() accepts a dict that maps column names to aggregation names.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
df = pd.DataFrame(
{
"price": [10, 12, 11, 15, 14, 13],
"volume": [100, 200, 150, 50, 300, 100],
},
index=idx,
)
out = df.resample("2D").agg({"price": "mean", "volume": "sum"})
print(out)The first bin (January 1 and 2) has a mean price of 11.0 and a volume of 300. The second bin has 13.0 and 200. The third has 13.5 and 400.
Three forms of agg() cover most needs:
- A dict of column to one function gives one output column per input column.
- A dict of column to a list of functions, such as
{"price": ["min", "max"], "volume": "sum"}, givesMultiIndexcolumns. - Named aggregation, shown below, gives flat columns with names you choose.
summary = df.resample("2D").agg(
avg_price=("price", "mean"),
last_price=("price", "last"),
total_volume=("volume", "sum"),
)
print(summary)Each keyword is the output column name, and each value is a (column, function) pair. Named aggregation avoids the MultiIndex cleanup that a list of functions requires, so prefer it for reports.
count versus size
Both count rows in a bin, but they treat missing values differently. count() skips NaN, and size() counts every row.
import numpy as np
import pandas as pd
idx = pd.date_range("2024-01-01", periods=4, freq="D")
s = pd.Series([1, np.nan, 3, 4], index=idx)
print(s.resample("2D").agg(["count", "size", "sum", "mean"])) count size sum mean
2024-01-01 1 2 1.0 1.0
2024-01-03 2 2 7.0 3.5In the first bin, sum and mean ignore the NaN. The mean is 1.0 because it divides by count, not by size. A large gap between count and size shows that the aggregate rests on little data.
first() and last() also skip nulls. If the last row of a bin is NaN, last() returns the last non-null value before it. That is often what you want for a balance, but it can hide a stale reading.
Ratios and weighted averages
Averaging an already-computed ratio gives the wrong answer when bins contain unequal weights. For a volume-weighted average price, sum the numerator and the denominator separately, then divide:
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
df = pd.DataFrame(
{
"price": [10, 12, 11, 15, 14, 13],
"volume": [100, 200, 150, 50, 300, 100],
},
index=idx,
)
df["notional"] = df["price"] * df["volume"]
g = df.resample("2D")[["notional", "volume"]].sum()
g["vwap"] = g["notional"] / g["volume"]
print(g)The first bin gives (10 × 100 + 12 × 200) / 300, about 11.33. A plain mean() of the two prices gives 11.0, which ignores that the second day traded twice the volume. The same pattern applies to conversion rates, defect rates, and any "per unit" figure.
Common errors
- Non-numeric columns.
df.resample("D").mean()raises aTypeErrorif the frame has a string column. Select the numeric columns first, for exampledf[["price", "volume"]], or aggregate the text column separately withfirst()ornunique(). - Unknown column in the dict. A key that is not a column name raises a
KeyError. Check spelling, and remember that a column used withon=is not available as an aggregation target in some versions. - Wrong rule for the whole frame.
df.resample("W").sum()silently sums prices. List each column inagg(), even when most use the same function. - Reading empty bins. A bin with no rows returns
0forsum()andNaNformean(). Treat this difference deliberately. The next chapters cover it in detail.
Exercise
Hourly readings are in a DataFrame with columns "temp" (degrees), "rainmm" (rainfall in that hour), and "reservoirlevel" (a level read at the end of each hour). Write the agg() call that gives daily results: the mean and maximum temperature, total rainfall, and the last reservoir level, with flat column names.
Show answer
df.resample("D").agg(meantemp=("temp", "mean"), maxtemp=("temp", "max"), totalrain=("rainmm", "sum"), endlevel=("reservoirlevel", "last")). Rainfall is a flow, so it is summed. Temperature is a level, so it uses mean and max. The reservoir level is a state, so last returns the final reading of the day. Named aggregation keeps the columns flat.
Exercise
A daily series has the values [5, NaN, NaN, 7] and you resample it with "2D". What do count(), size(), and sum() return for the first bin, which holds [5, NaN]?
Show answer
count() returns 1 because it skips NaN. size() returns 2 because it counts every row. sum() returns 5.0 because NaN is skipped by default.