Resampling Time Series
Resampling changes the frequency of a time series. Downsampling aggregates fine-grained data into bigger periods (minutes → hours, days → months). Upsampling goes the other way and has to fill the new, empty slots. resample() is essentially a groupby on time buckets, and it needs a DatetimeIndex (or a datetime column passed with on=).
Downsampling: days to weeks and months
import pandas as pd
days = pd.date_range("2024-01-01", "2024-03-31", freq="D")
orders = pd.Series([20 + d.month * 5 + (d.dayofyear * 37) % 23 for d in days],
index=days, name="orders")
print(orders.resample("ME").sum())
print(orders.resample("W").mean().round(1).head(4))2024-01-31 1118
2024-02-29 1192
2024-03-31 1432
Freq: ME, Name: orders, dtype: int64
2024-01-07 35.0
2024-01-14 37.7
2024-01-21 37.1
2024-01-28 33.3
Freq: W-SUN, Name: orders, dtype: float64
Common frequency codes:
| Code | Period |
|---|---|
"min", "h" |
minute, hour |
"D" |
calendar day |
"W" |
week (ending Sunday by default; "W-MON" ends on Monday) |
"ME", "MS" |
month, labelled at month end / month start |
"QE", "YE" |
quarter end, year end |
"15min", "2h" |
multiples work too |
The labels for "ME" are the last day of each month. In pandas versions before 2.2 the codes were "M", "Q" and "Y".
Several aggregations: OHLC and agg()
import pandas as pd
ticks = pd.Series([10.0, 10.4, 10.1, 10.8, 11.0, 10.7, 10.9, 11.3, 11.1],
index=pd.date_range("2024-06-03 09:00", periods=9, freq="20min"),
name="price")
print(ticks.resample("h").ohlc())
print(ticks.resample("h").agg(["mean", "count"]).round(2)) open high low close
2024-06-03 09:00:00 10.0 10.4 10.0 10.1
2024-06-03 10:00:00 10.8 11.0 10.7 10.7
2024-06-03 11:00:00 10.9 11.3 10.9 11.1
mean count
2024-06-03 09:00:00 10.17 3
2024-06-03 10:00:00 10.83 3
2024-06-03 11:00:00 11.10 3
ohlc() gives the open, high, low and close of each period, the standard summary for price data.
Resampling a DataFrame column with on=
If the dates are a column rather than the index, name it with on=. Different columns can get different aggregations:
import pandas as pd
events = pd.DataFrame({
"time": pd.to_datetime(["2024-07-01 08:10", "2024-07-01 08:40", "2024-07-01 09:05",
"2024-07-01 11:20", "2024-07-01 11:45"]),
"user": ["u1", "u2", "u1", "u3", "u1"],
"bytes": [1200, 560, 3400, 800, 950],
})
hourly = events.resample("h", on="time").agg({"user": "nunique", "bytes": "sum"})
print(hourly) user bytes
time
2024-07-01 08:00:00 2 1760
2024-07-01 09:00:00 1 3400
2024-07-01 10:00:00 0 0
2024-07-01 11:00:00 2 1750
The 10:00 hour had no events, but it still appears with zero values, so a regular timeline has no gaps.
Upsampling and filling
Going to a finer frequency creates empty slots. Fill them by carrying values forward (ffill) or interpolating:
import pandas as pd
weekly = pd.Series([80.0, 86.0, 83.0],
index=pd.to_datetime(["2024-02-05", "2024-02-12", "2024-02-19"]),
name="weight_kg")
daily = weekly.resample("D")
print(pd.DataFrame({
"asfreq": daily.asfreq(),
"ffill": daily.ffill(),
"interpolate": daily.interpolate().round(2),
}).head(8)) asfreq ffill interpolate
2024-02-05 80.0 80.0 80.00
2024-02-06 NaN 80.0 80.86
2024-02-07 NaN 80.0 81.71
2024-02-08 NaN 80.0 82.57
2024-02-09 NaN 80.0 83.43
2024-02-10 NaN 80.0 84.29
2024-02-11 NaN 80.0 85.14
2024-02-12 86.0 86.0 86.00
Plotting a resampled series
Resampling is often the step right before a chart, turning noisy daily values into clear monthly bars:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(3)
days = pd.date_range("2024-01-01", "2024-12-31", freq="D")
season = 12 + 10 * np.sin((days.dayofyear - 105) / 365 * 2 * np.pi)
temps = pd.Series(season + rng.normal(0, 2.5, len(days)), index=days)
monthly = temps.resample("ME").mean()
monthly.index = monthly.index.strftime("%b")
monthly.plot(kind="bar", rot=0, color="tab:orange", title="Mean daily temperature (°C)")
plt.show()
print("Warmest month:", monthly.idxmax(), round(monthly.max(), 1))Warmest month: Jul 22.0
Test yourself
What does s.resample("ME").sum() do with daily data?
- Adds a column per month
- Totals the values within each calendar month
- Keeps only month-end values
- Shifts the data by a month
What does resample require?
- A sorted string column
- A DatetimeIndex, or a datetime column passed with on=
- A MultiIndex
- Numeric columns only
Which result does resample("h").ohlc() produce for each hour?
- Only the mean
- Open, high, low and close
- The number of rows
- One column per minute