Sub topic 4
Downsampling: from daily to weekly or monthly
This chapter assumes you can build a DatetimeIndex and read frequency strings such as "W" and "MS". Both were covered in earlier chapters. Here you will use them to reduce daily data to a coarser frequency.
What downsampling does
Downsampling moves data to a coarser frequency, for example daily rows to weekly rows. Several input rows fall into each output bin, so you must say how to combine them. The pattern is always resample(rule) followed by an aggregation such as sum() or mean().
Daily to weekly
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" is short for "W-SUN". Each bin ends on a Sunday and is labeled with that Sunday. The first bin covers 2024-01-01 to 2024-01-07, so it holds 0+1+...+6 = 21. The second bin has only three rows (7, 8, 9), so it sums to 24. The last bin is still emitted even though the week is incomplete.
To end weeks on another day, use an anchored alias such as "W-FRI".
Daily to monthly with different aggregations
Prices are usually averaged and volumes summed. Pass a dict to agg() to choose an aggregation for each 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": "mean", "volume": "sum"})
print(monthly)The output is:
price volume
2024-01-01 15.0 310
2024-02-01 45.0 290
2024-03-01 74.5 300"MS" means month start, so each bin begins on the first of the month and carries that date as its label. February has 29 days in 2024, which is why its volume is 290. The result is indexed by month start, not by the last day.
Month start or month end
| Alias | Bin boundary | Label |
|---|---|---|
| `"MS"` | First day of month | First day of month |
| `"ME"` | Last day of month | Last day of month |
In pandas 2.2 and later, "ME" replaces the old "M" alias, and "M" raises a deprecation warning. On older versions, use "M". Choose the alias that matches how you plan to join or plot the result.
Common errors
- TypeError about the index.
resample()needs aDatetimeIndex, or a column named throughon=. Convert withpd.to_datetime()andset_index()first. - Aggregating text columns.
df.resample("MS").mean()fails or drops columns that are not numeric. Select the numeric columns, or useagg()with a dict. - Forgetting the aggregation.
s.resample("W")returns aResamplerobject, not data. Nothing is computed until you callsum(),mean(),agg(), or a similar method. - Using
sum()wherelast()is meant. A closing balance or an end-of-day price is a snapshot, not an amount that accumulates. Uselast()for snapshots.
Exercise
A daily Series s has a DatetimeIndex starting on Wednesday 2024-01-03. You call s.resample("W").sum(). On what date is the first bin labeled, and which rows does it contain?
Show answer
The first bin is labeled Sunday 2024-01-07. It contains the rows from 2024-01-03 (Wednesday) through 2024-01-07, which is five rows. The bin is partial because the data starts mid-week, and it is aggregated like any other bin.
Exercise
You have daily columns temp and rain. Write the call that gives monthly-start rows with the mean of temp and the total of rain.
Show answer
df.resample("MS").agg({"temp": "mean", "rain": "sum"})