Sub topic 1
Start with a DatetimeIndex
Prerequisites
This chapter assumes basic Python, pandas Series and DataFrame use, indexing, and familiarity with dates and times. A DatetimeIndex is an index whose values are pandas timestamps. resample() uses this time index to group observations into time periods.
Start with a DatetimeIndex
Convert text dates with pd.to_datetime(), then set the result as the index:
import pandas as pd
df = pd.DataFrame({
"date": ["2024-01-01", "2024-01-02", "2024-01-03"],
"sales": [10, 12, 8],
})
df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date")
daily = df.resample("D").sum()
print(daily)The index must contain dates or times and should normally be sorted. You can also resample a date column directly with on="date" when changing the index is inconvenient.
Frequency strings: describing the target frequency
A frequency string describes the size of each time period.
"D"means calendar day."W"means week."MS"means month start."h"means hour."min"means minute.
The choice depends on the meaning of the data. For example, use "MS" when monthly results should be labeled by the first day of each month.
How `resample()` groups rows into bins
Calling df.resample("W") creates a Resampler object. It divides the time index into weekly bins. An aggregation method, such as sum() or mean(), then reduces each bin to one result.
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)By default, weekly bins end on Sunday and the result is labeled with that Sunday. The first result is 0 + 1 + ... + 6, or 21.
Downsampling: from daily to weekly or monthly
Downsampling changes a fine frequency to a coarser one. Pick an aggregation that matches the measurement:
sum()for totals such as sales.mean()for averages such as temperature.min()ormax()for limits.ohlc()for open, high, low, and close values.
Exercise
Which expression calculates monthly sales totals when date is the index?
Show answer
df.resample("MS")["sales"].sum()