Sub topic 4
Downsampling: from daily to weekly or monthly
Downsampling means moving a time series to a coarser frequency, such as daily rows to weekly or monthly rows. Several input rows collapse into one output row, so you must choose how to combine them. This chapter assumes you can build a DatetimeIndex, read frequency strings such as "D" and "W", and index a Series or DataFrame. Earlier chapters cover those topics.
The shape of a downsample
resample() does nothing by itself. It returns a Resampler object that knows how to split the index into bins. The data is only reduced when you call an aggregation such as sum(), mean(), or agg(). Each bin becomes one output row, and the output index holds one label per bin.
Daily to weekly
The first example uses ten consecutive days. January 1, 2024 is a Monday.
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)2024-01-07 21
2024-01-14 24
Freq: W-SUN, dtype: int64The alias "W" means "W-SUN": weeks that end on Sunday. The first bin holds Monday January 1 through Sunday January 7, so it sums 0 through 6 to get 21. The second bin holds January 8 through 10 and sums 7, 8 and 9 to get 24.
Two details matter here:
- The second bin is incomplete. The data stops on Wednesday, but the bin is still labeled Sunday, January 14, a date that is not in your data. Resampling never shortens a bin or marks it as partial.
- The label is the right edge of the bin. Anyone reading the output as "the week starting January 7" will be off by a week.
Checking how complete each bin is
Because partial bins are silent, a useful habit is to compute a count next to every aggregate. agg() accepts a list of function names.
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").agg(["sum", "count"])) sum count
2024-01-07 21 7
2024-01-14 24 3A count of 3 in a bin that should hold 7 rows tells you the sum is not comparable with the other weeks. This matters most for sum(), which grows with the number of rows, and less for mean().
Weeks that start on Monday
Many reports label a week by its first day. The default bins are right-closed and right-labeled, so you need to change both. Anchor the week to Monday, then ask for left-closed, left-labeled bins.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=10, freq="D")
s = pd.Series(range(10), index=idx)
monday_weeks = s.resample("W-MON", closed="left", label="left").agg(["sum", "count"])
print(monday_weeks) sum count
2024-01-01 21 7
2024-01-08 24 3Now each bin is the half-open interval from one Monday up to, but not including, the next Monday. The label is the Monday that opens the bin. The totals match the first example, but the labels now name the first day of each week. The closed and label options get their own chapter. For now, treat them as the controls that decide which edge belongs to a bin and which edge names it.
Daily to monthly
For months, you choose between a start-anchored and an end-anchored alias.
| Alias | Meaning | Default `closed` | Default `label` | Label example |
|---|---|---|---|---|
| `"W"` or `"W-SUN"` | Weeks ending Sunday | right | right | 2024-01-07 |
| `"MS"` | Month start | left | left | 2024-01-01 |
| `"ME"` | Month end | right | right | 2024-01-31 |
| `"QS"` | Quarter start | left | left | 2024-01-01 |
| `"YS"` | Year start | left | left | 2024-01-01 |
The pattern is that start-anchored aliases are left/left and end-anchored aliases are right/right. For month-end bins on daily data, pandas still includes the whole last day in the bin, so January 31 belongs to the January bin.
This example uses "MS" on 90 days of data, which covers all of January and February (a leap year) and 30 days of March.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=90, freq="D")
s = pd.Series(range(90), index=idx)
print(s.resample("MS").agg(["sum", "count"])) sum count
2024-01-01 465 31
2024-02-01 1305 29
2024-03-01 2235 30The counts (31, 29, 30) follow the calendar, not a fixed number of days. This is the main difference from a fixed window. A weekly bin always spans seven days, while a monthly bin spans 28 to 31 days. A monthly sum() of a daily quantity therefore favors long months, and a monthly mean() does not.
Choosing the aggregation
The aggregation should match what the numbers mean. The same daily data can need different reductions depending on its type.
| Kind of daily value | Typical reduction | Reason |
|---|---|---|
| Flow (sales, rainfall, visits) | `sum()` | Totals add up across days |
| Level or rate (temperature, price) | `mean()` | Averages stay on the same scale |
| Stock (account balance, inventory) | `last()` | The value at the end of the period is the meaningful one |
| Extremes | `max()`, `min()` | Peaks and troughs |
| Rows per period | `count()` or `size()` | Data quality and activity |
count() ignores NaN values, while size() counts every row in the bin. If your daily data has gaps, the two give different answers, and comparing them shows how much is missing.
You can also apply different reductions to different columns by passing a dict to agg(). A later chapter covers that and ohlc(). Chaining a column selection first is the shorter way to resample a single column:
import pandas as pd
idx = pd.date_range("2024-01-01", periods=90, freq="D")
df = pd.DataFrame({"sales": [5] * 90, "temp": range(90)}, index=idx)
print(df["sales"].resample("MS").sum())
print(df.resample("MS").last())The first call returns a Series of monthly sales totals (155, 145 and 150). The second returns the last row of each month, which is the whole DataFrame reduced with one rule.
Common errors
- A
TypeErrorabout the index.resample()needs aDatetimeIndex,PeriodIndexorTimedeltaIndex. If your dates are in a column, either callset_index()first or passon="date". Convert strings withpd.to_datetime()first. - Unsorted data. Resampling does not require sorted input, but the output is sorted by bin. Duplicate timestamps are allowed and are simply aggregated together.
- Reading the label as the start. Weekly and month-end labels are the last day of the period. Use
label="left"with an appropriateclosed, or a start-anchored alias, when you want the first day. - Trusting the last bin. The final bin often covers fewer days than the others. Compare its count to earlier bins before you plot it as a full period.
- Mean of means. Averaging weekly means to get a monthly figure weights each week equally, even if one week has fewer rows. Resample the original daily data instead.
Exercises
Exercise
A daily Series s of sales starts on Wednesday, 2024-01-03, and runs for 12 days. You call s.resample("W").sum(). How many output rows do you get, what is the label of the first one, and how many daily rows does that first bin contain?
Show answer
You get 3 rows. The data covers Wednesday January 3 through Sunday January 14. The first bin ends on Sunday January 7, so it is labeled 2024-01-07 and contains 5 daily rows (Wednesday through Sunday). The second bin, labeled 2024-01-14, contains 7 rows (Monday through Sunday). That adds up to 12 rows, so the data ends exactly on a Sunday, and the result has only 2 rows. The correct answer is therefore 2 rows: 2024-01-07 with 5 rows and 2024-01-14 with 7 rows.
Exercise
You have daily closing balances in a Series bal and want one value per calendar month, labeled with the first day of the month. Which call do you use, and why is sum() the wrong choice here?
Show answer
Use bal.resample("MS").last(). A balance is a stock, so the meaningful monthly value is the one at the end of the month. sum() would add up the balance across all days, producing a number that depends on how many days the month has and has no real meaning.