Sub topic 3
Which Side of the Bin Is Closed, and How Bins Are Labeled
Assume you know basic pandas indexing and date-time types. The examples use a DatetimeIndex, which stores timestamps as an index.
Bin edges and labels
resample() divides timestamps into time bins. closed chooses which edge belongs to a bin. label chooses the timestamp used to name the result.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=4, freq="D")
s = pd.Series(range(4), index=idx)
print(s.resample("2D", closed="left", label="left").sum())
print(s.resample("2D", closed="right", label="right").sum())With closed="left", a bin includes its left edge and excludes its right edge. With label="right", the result is indexed by the right edge. Defaults vary by frequency, so set these arguments explicitly when boundary behavior matters.
Empty bins and missing values
A frequency can create bins containing no rows. Aggregations handle them differently. sum() commonly returns 0, while mean() returns NaN. Use min_count=1 when an empty sum should remain missing:
monthly = df.resample("MS")["sales"].sum(min_count=1)This distinguishes “no observations” from “observed values whose total is zero.”
Resampling on a column
The time column does not need to be the index. Pass it with on=:
monthly = df.resample("MS", on="date")["sales"].sum()For a MultiIndex, use level= instead.
Choosing the time operation
resample()groups timestamps into non-overlapping calendar bins and aggregates them.asfreq()selects or creates values at an exact regular frequency without aggregation.rolling()calculates overlapping moving-window statistics, such as a seven-day moving mean.
Aligning bins
Use origin to choose the reference point for bins and offset to shift that reference. For example, origin="start_day", offset="6h" starts daily bins at 06:00 rather than midnight.
Resampling within groups
Group first, then resample:
result = (
df.groupby("store")
.resample("D", on="date")["sales"]
.sum()
)The result usually has a MultiIndex containing the group and timestamp.
Time zones and periods
Timezone-aware data keeps its timezone while resampling. Daylight saving transitions can create a local day with 23 or 25 hours, so use a clear timezone and inspect transition dates.
A PeriodIndex represents spans such as months rather than instants. It can also be resampled, but choose convention="start" or "end" when converting between period frequencies.
Exercise
Which method should you use for a seven-day moving average?
Show answer
Use rolling(), because its windows overlap. Use resample() for separate calendar bins.