skip to content

Resampling and Windows

resample buckets rows by a rule such as ME or h, while rolling, expanding and ewm compute moving statistics. Interviewers ask resample versus rolling and how closed and label work.

on this pageshow

questions

6

In pandas, how do you roll minute-level web traffic up to hourly and daily totals with resample, and what does the result look like?

level: juniorimportance: must knowfreq 70%

answer

  1. a groupby keyed on time
  2. rule string, then an aggregation
  3. one row per bucket
  4. labelled by the bucket's start
  5. empty hour sums to 0

basics

~10 s

Call resample with a rule on a frame that has a DatetimeIndex, then aggregate: traffic.resample('h').sum() and traffic.resample('D').sum(). The result has one row per hour or day, stamped with each bucket's start time.

solid answer

~30 s

`resample` is a groupby keyed on time: `traffic.resample('h')` returns a `Resampler`, and nothing is computed until you call an aggregation such as `.sum()`, `.mean()` or `.agg(...)`. The frame needs a `DatetimeIndex` (or `on='ts'` for a datetime column), otherwise pandas raises a `TypeError`. For `'h'` and `'D'` each row is stamped with the bucket's start, so `09:00` holds 09:00 to 09:59. Every bucket between the first and last timestamp appears, even an empty one: `sum()` gives `0` there because `min_count` defaults to 0, while `mean()` gives `NaN`. To aggregate columns differently, pass a dict: `.agg({'visits': 'sum', 'errors': 'max'})`.

code

python · 15 lines
python
import numpy as np
import pandas as pd

idx = pd.date_range("2026-03-02 00:00", periods=3 * 24 * 60, freq="min")
rng = np.random.default_rng(0)
traffic = pd.DataFrame(
    {"visits": rng.poisson(20, len(idx)), "errors": rng.poisson(1, len(idx))},
    index=idx,
)

hourly = traffic.resample("h").sum()
daily = traffic.resample("D").agg({"visits": "sum", "errors": "max"})

print(hourly.shape, daily.shape)  # (72, 2) (3, 2)
print(daily.index[0])             # 2026-03-02 00:00:00

go deeper

for a junior

Know the two steps: resample with a rule such as 'h' or 'D', then an aggregation like sum or mean. Mention that the frame needs a DatetimeIndex or on= naming a datetime column.

for a middle

Explain the result's shape: one row per bucket, empty buckets kept, sum giving 0 and mean giving NaN for them, and how a dict passed to agg aggregates columns differently.

for a senior

Show you would check min_count on totals so an outage does not read as zero traffic, and that you know which rules stamp a bucket by its start and which by its end.

for a principal

Connect the default stamping and empty-bucket handling to how downstream dashboards read the numbers, and push for explicit rules and min_count in shared reporting code.

## What `resample` does `resample` turns rows at one frequency into rows at another by **grouping on time**. You can read `traffic.resample('h').sum()` as "group the rows by which hour they fall in, then sum each group". Two steps are involved: 1. `traffic.resample('h')` builds a **`Resampler`** object. It holds the bucket definition and computes nothing yet. 2. An aggregation on it, such as `.sum()`, `.mean()`, `.max()`, `.count()`, `.ohlc()` or `.agg(...)`, produces the new `DataFrame` or `Series`. The object being resampled must carry time somewhere pandas can find it: - a **`DatetimeIndex`** (also `TimedeltaIndex` or `PeriodIndex`) as the row index, which is the usual case; - or a datetime column named with `on=`, as in `df.resample('D', on='ts')`; - or a datetime level of a `MultiIndex` named with `level=`. With none of these, pandas raises `TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'`. ## Rules for the usual buckets The first argument is a **frequency alias** (or an offset object). The ones a traffic report reaches for: | rule | bucket | default stamp | |---|---|---| | `'min'`, `'15min'` | one or fifteen minutes | bucket start | | `'h'`, `'6h'` | one or six hours | bucket start | | `'D'` | calendar day | midnight that starts the day | | `'W'` | week ending Sunday | the Sunday that ends the week | | `'ME'`, `'QE'`, `'YE'` | month, quarter, year end | the last day of the period | | `'MS'`, `'QS'`, `'YS'` | month, quarter, year start | the first day of the period | The aliases are case-sensitive: hours are lowercase `'h'` and minutes `'min'`. A number in front multiplies the bucket (`'15min'`, `'6h'`). The defaults for which edge closes a bucket and which edge stamps it differ between the start-labelled rules and the end-labelled ones; the `closed` and `label` arguments override them. ## Aggregating: one function, a list, or a dict - **One method** applies to every numeric column: `traffic.resample('h').sum()`. - **A list** produces several statistics per column under a two-level column index: `traffic.resample('D').agg(['sum', 'max'])`. - **A dict** chooses per column: `traffic.resample('D').agg({'visits': 'sum', 'errors': 'max'})`. This is how you total visits while keeping the worst error minute. - **Select first** to aggregate one column: `traffic['visits'].resample('h').sum()` returns a `Series`. Use the string names (`'sum'`, `'mean'`) so pandas runs its own grouped implementation. ## The shape of the result - **One row per bucket**, from the bucket holding the first timestamp to the one holding the last. Three full days of minute data become 72 hourly rows or 3 daily rows. - The new index is a `DatetimeIndex` with the rule as its `freq`. - **Empty buckets are kept**, not dropped. If the logging service was down for an hour, that hour still appears. What it holds depends on the aggregation: - `sum()` returns `0`, because `Resampler.sum` has `min_count=0` by default; pass `min_count=1` to get `NaN` instead, which is often more honest for an outage; - `mean()`, `max()` and `first()` return `NaN`; - `count()` and `size()` return `0`. - The row count drops: resampling down from minutes to hours **shrinks** the frame, which is the main difference from `rolling`, which keeps one output row per input row. ## A worked traffic example Minute rows from Monday 2 March 2026 00:00 to Wednesday 4 March 23:59 give 4,320 rows. `resample('h').sum()` returns 72 rows stamped `2026-03-02 00:00`, `01:00` and so on; `resample('D').agg({'visits': 'sum', 'errors': 'max'})` returns 3 rows stamped at each midnight. If the minute data sit in a column `ts` rather than the index, `traffic.resample('D', on='ts').sum()` gives the same daily totals with `ts` as the result's index. ## Per-group totals A traffic log usually covers several sites or pages. `df.groupby('site').resample('h', on='ts')['visits'].sum()` resamples each site separately and returns a `Series` with a `MultiIndex` of site and hour. Each site gets its own run of buckets from its own first to last timestamp, so a site that went live on Tuesday has no Monday rows. When every site must share one hourly grid, unstack the result or reindex it against a single `date_range`. ## Where people go wrong - Calling `resample` on a frame whose time is still a string column: convert it first and set it as the index or name it with `on=`. - Expecting `resample('h')` to return numbers: it returns a `Resampler` until you aggregate. - Reading a `0` in an hourly total as "no visitors" when it may mean "no rows arrived"; `min_count=1` separates the two. - Using `asfreq('h')` to downsample: it picks the single value stamped exactly on each hour and sums nothing.

  • An hourly total shows 0 for an hour when the tracker was offline. How do you make that hour show missing instead?
    Pass `min_count=1`: `traffic['visits'].resample('h').sum(min_count=1)`. `Resampler.sum` defaults to `min_count=0`, so an empty bucket sums to 0; with `min_count=1` a bucket needs at least one non-missing value, and an empty one becomes `NaN`, which keeps an outage distinguishable from a quiet hour.
  • How does the result of `traffic.resample('h').sum()` differ in shape from `traffic.rolling('h').sum()`?
    `resample` returns one row per hour bucket, so 4,320 minute rows become 72. `rolling('h')` returns one row per input row, each holding the total of the hour ending at that minute, so the frame keeps its 4,320 rows. Use resample for a report at a new frequency and rolling for a moving statistic at the original one.

  • resample('h') returns the summed frame directly
  • Empty hours are dropped from a resampled result
  • An empty bucket's sum is NaN by default
  • resample works on any frame with a timestamp column, no setup needed
  • asfreq('D') gives daily totals
open as a page

In pandas, how do `rolling(7)` and `rolling('7D')` differ for a 7-day moving average of daily traffic that has missing days?

level: middleimportance: must knowfreq 65%

basics

~10 s

rolling(7) averages the last seven rows, however many days they span; rolling('7D') averages every row in the seven days ending at each timestamp. With missing days, only the offset window really means a week.

open as a page

In pandas, how do `asfreq` and `resample` differ when you change a series' frequency, and how do you fill the gaps after upsampling?

level: middleimportance: should knowfreq 42%

basics

~20 s

asfreq reindexes to the new frequency and keeps only values stamped exactly on the new timestamps; resample groups rows into buckets and aggregates them. After upsampling, new rows are NaN until you ffill, bfill or interpolate them.

open as a page

In pandas, why does `resample('W')` stamp weekly traffic totals with Sundays while `resample('h')` stamps each hour by its start, and how do `closed` and `label` change that?

level: seniorimportance: should knowfreq 38%

basics

~20 s

closed and label default to 'left' except for end-anchored rules ME, QE, YE, BME, BQE, BYE and W, which default to 'right'. So 'W' (W-SUN) buckets Monday to Sunday and stamps the Sunday; pass closed and label to change it.

open as a page

In pandas, how do `ewm(span=...)`, `ewm(halflife=...)` and `adjust` shape an exponentially weighted trend of daily web traffic?

level: seniorimportance: should knowfreq 30%

basics

~20 s

span and halflife are two ways to set the decay alpha (2/(span+1), or the weight halving every halflife rows); pass exactly one. adjust=True, the default, normalises weights over the available history; adjust=False uses the recursive form starting from the first value.

open as a page

A pandas 2.x pipeline calls `resample('M')` and `resample('H')`; what happens when it runs on pandas 3.0, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

In pandas 3.0 both raise ValueError: Invalid frequency. The aliases were removed: use 'ME' for month end (also QE, YE, BME, BQE, BYE, SME, CBME) and lowercase 'h' for hours (also min, ms, us, ns for T, L, U, N).

open as a page