Sub topic 5
Choosing aggregations, including ohlc and per-column agg
This chapter assumes you can build a DatetimeIndex and call resample() on a Series or DataFrame. When you downsample, each bin holds several rows. The aggregation decides which single value or values represent that bin.
Match the aggregation to the data
The right function depends on what the column measures.
| Column holds | Typical aggregation | Reason |
|---|---|---|
| Amounts that add up (sales, volume) | `sum` | Weekly sales are the sum of daily sales. |
| Levels or rates (temperature, price) | `mean`, `last` | Adding temperatures has no meaning. |
| Running totals or balances | `last` | The end-of-period value is the answer. |
| Extremes | `min`, `max` | Keep the range of the bin. |
| Counts of observations | `count`, `size` | `count` skips NaN, `size` does not. |
A wrong choice runs without error and gives plausible numbers. Summing a price column is the usual example.
Summarizing a bin with ohlc
ohlc() returns four columns for each bin: the first value (open), the highest (high), the lowest (low), and the last (close). It comes from financial data, but it works on any Series where the start, end, and range of each period matter.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
price = pd.Series([10, 12, 9, 11, 14, 13], index=idx)
print(price.resample("3D").ohlc())The first bin holds 10, 12, 9, so it gives open 10, high 12, low 9, close 9. The second bin holds 11, 14, 13, so it gives open 11, high 14, low 11, close 13.
Different aggregations per column
A DataFrame usually mixes column types. Pass a dict to agg(), with column names as keys and aggregations as values. Use a list as a value to get several results for one column.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=90, freq="D")
df = pd.DataFrame(
{"price": range(90), "volume": [10] * 90},
index=idx,
)
monthly = df.resample("MS").agg(
{"price": ["min", "max", "mean"], "volume": "sum"}
)
print(monthly)
print(monthly.columns.tolist())When any value is a list, the result has two-level column labels such as ("price", "max"). Flatten them if you need plain names:
monthly.columns = ["_".join(col) for col in monthly.columns]A column you leave out of the dict is dropped from the result. You can also pass a custom function, such as lambda x: x.max() - x.min(). Built-in names like "sum" are faster, so use a custom function only when no built-in fits.
Common errors
- Aggregating non-numeric columns.
df.resample("MS").mean()raises aTypeErrorif a text column is present. Select the numeric columns first, or useagg()with a dict. - Using
ohlc()on a DataFrame with several columns. The result gets two-level columns, one set per input column. Select one column first, as indf["price"].resample("D").ohlc(). - Mixing up
countandsize.countignores NaN values, so it answers "how many valid readings?".sizecounts every row in the bin.
Exercise
A DataFrame df has a DatetimeIndex and the columns temp (hourly temperature) and rain_mm (hourly rainfall). Write the call that gives one row per day with the daily maximum temperature and the total rainfall.
Show answer
df.resample("D").agg({"temp": "max", "rain_mm": "sum"}). Temperature is a level, so take its maximum. Rainfall is a flow that adds up, so sum it.