Resampling
resample changes the time frequency of data, such as turning daily numbers into weekly totals.
In this page:
Syntax
df.resample("W").sum()
df.resample("M")["column"].mean()
Resampling
resample("W") groups a datetime-indexed series into weekly bins and needs an aggregation like sum or mean. Downsampling reduces frequency, while upsampling increases it and creates gaps to fill with ffill or interpolate.
Common rules include "D", "W" and "2D".
Note:
resample is groupby for time.
Example: Resampling
import pandas as pd
idx = pd.date_range("2024-01-01", periods=6, freq="D")
s = pd.Series([1, 2, 3, 4, 5, 6], index=idx)
print(s.resample("2D").sum())
print(s.resample("W").mean())
# Output:
# 2024-01-01 3
# 2024-01-03 7
# 2024-01-05 11
# Freq: 2D, dtype: int64
# 2024-01-07 3.5
# Freq: W-SUN, dtype: float64
Related Topics
Common Mistakes
- Forgetting an aggregation
- Resampling without a DatetimeIndex
- Not filling gaps when upsampling
Chapter Summary
- resample regroups by time frequency
- It needs a datetime index
- Downsampling aggregates
- Upsampling needs filling
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: