In pandas, how do `rolling(7)` and `rolling('7D')` differ for a 7-day moving average of daily traffic that has missing days?
answer
- rows versus time
- gaps change what a window covers
- min_periods defaults differ
- offset windows need a sorted index
basics
~10 srolling(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.
solid answer
~40 sAn integer window counts **rows**: `daily.rolling(7).mean()` always uses the last seven observations, so with three missing dates it can span ten calendar days. A string or offset window counts **time**: `daily.rolling('7D').mean()` uses every row in `(t - 7 days, t]`, so the number of rows varies. The defaults differ too: `min_periods` is the window size for an integer window, giving six leading `NaN`s, and 1 for an offset window, so the first rows are averages of whatever exists. Offset windows need a monotonic `DatetimeIndex` (or `on=` naming a datetime column) and raise `ValueError` otherwise. `center=True` moves the label to the middle of the window in both forms.
code
python · 14 linesimport pandas as pd
days = pd.to_datetime([
"2026-03-01", "2026-03-02", "2026-03-03",
"2026-03-06", "2026-03-07", "2026-03-08", "2026-03-09", "2026-03-10",
])
daily = pd.Series([100, 120, 110, 90, 95, 130, 125, 140], index=days)
out = pd.DataFrame({
"visits": daily,
"rows7": daily.rolling(7).mean(), # last 7 rows, any span
"days7": daily.rolling("7D").mean(), # rows in (t - 7 days, t]
})
print(out)go deeper
Remember the split: an integer window counts rows, a string like '7D' counts time and needs datetime timestamps.
Explain how gaps change each window, the two different min_periods defaults, and why the offset form needs a sorted DatetimeIndex.
Show you would resample to a complete daily grid or choose the offset window deliberately, set min_periods so early or gappy weeks are not reported as full, and avoid center=True for features used in prediction.
Treat the window definition as part of a metric's contract: a shared '7-day average' should state whether it means rows or days and how it handles partial weeks, so reports agree.
## Two ways to say "seven" `Series.rolling` and `DataFrame.rolling` take a `window` argument that can mean two different things: - **An integer** is a count of **rows**. `rolling(7)` looks at the current row and the six before it, whatever their timestamps. - **A string, `Timedelta` or offset** is a span of **time**. `rolling('7D')` looks at every row whose timestamp falls in the seven days ending at the current row. It is only valid on a datetime-like index, or with `on=` naming a datetime column. On a complete daily series the two agree. They part ways the moment dates are missing, which in web traffic means a tracker outage, a holiday with no export, or a filter that dropped zero-traffic days. | | `rolling(7)` | `rolling('7D')` | |---|---|---| | window measured in | rows | time | | rows per window | always 7 | varies with gaps | | default `min_periods` | 7 (the window size) | 1 | | needs a sorted datetime index | no | yes, else `ValueError` | | `step=` allowed | yes | no (`NotImplementedError`) | | default `closed` | `'right'` | `'right'`, i.e. `(t - 7D, t]` | ## What each one computes on gappy data Take eight daily totals with 4 and 5 March missing. On 10 March: 1. `rolling(7)` averages the seven rows from 2 March to 10 March, nine calendar days. 2. `rolling('7D')` averages the rows after 3 March up to 10 March. Since `closed` defaults to `'right'`, the window is `(3 March, 10 March]`, which holds five rows. So the row-count window silently stretches across the gap, while the time window shrinks to the data it actually has. For a "7-day average" in a report, the time window is the one whose meaning matches its name. ## `min_periods`: when a value appears `min_periods` is the minimum number of non-missing observations a window needs before pandas returns a number instead of `NaN`. - For an **integer** window it defaults to the window size, so `rolling(7)` returns `NaN` for the first six rows and for any window holding a `NaN`. - For an **offset** window it defaults to **1**, so `rolling('7D')` returns a value from the first row on, even though that value is an average of one day. Neither default is wrong, but both surprise people. Set it explicitly when the edge matters: `rolling('7D', min_periods=5)` refuses to report a weekly average built from fewer than five days, and `rolling(7, min_periods=1)` lets a dashboard draw a line from day one. ## `center`, `closed` and the label By default the result at time `t` describes the window **ending** at `t`. `center=True` places the label at the middle of the window instead; it works for integer windows and, per the window user guide, for datetime-like offset windows too. A centred window uses future rows, so it suits smoothing a chart and does not suit a feature computed for a prediction at `t`. `closed` sets which ends of the window are included: `'right'` (default), `'left'`, `'both'` or `'neither'`. `rolling('7D', closed='left')` gives the seven days **before** today, excluding today's row. ## Practical rules - Before an offset window, sort the index: `daily.sort_index().rolling('7D')`. pandas checks that the index is monotonic and free of `NaT` and raises `ValueError: index values must be monotonic` otherwise. - If the timestamps are a column, use `df.rolling('7D', on='day')` instead of setting the index. - If you need one row per calendar day, including zero days, `resample('D').sum()` first and then `rolling(7)`: after resampling, rows and days line up and the two forms agree again. - For one moving average **per site or per page**, use `df.groupby('site').rolling('7D', on='day').mean()`, which restarts the window for each group and returns a `MultiIndex` of group key and original row label. - Window results on numeric data come back as `float64`, as the window user guide notes. ## Rolling versus resample Both take an offset, but they answer different questions. `resample('7D')` cuts the timeline into fixed, non-overlapping buckets and returns one row per bucket. `rolling('7D')` slides a window to every row and returns one result per row. A weekly report is a resample; a 7-day moving average on a daily chart is a rolling window.
- How do you compute a 7-day moving average separately for each site in a frame with columns `site`, `day` and `visits`?Sort by site and day, then `df.groupby('site').rolling('7D', on='day')['visits'].mean()`. The window restarts inside each group, and each group's `day` values must be monotonic. The result carries a `MultiIndex` of the site and the original row label, so join it back on that, or `reset_index(level=0, drop=True)` to align with `df`.
- What do `shift(1)` and `diff(1)` add next to a moving average?`daily.shift(1)` moves values down one row, so each row sees yesterday's total; `daily.diff(1)` is `daily - daily.shift(1)`, the day-over-day change. Both count rows, not days, so with gaps they compare against the previous row; `shift(freq='D')` moves the index by a day instead of moving the values.
- Why might `rolling('7D')` and `rolling(7)` still disagree after you `resample('D').sum()` the data?They agree on values once every calendar day has a row, but not at the start: `rolling(7)` waits for seven rows because its `min_periods` defaults to 7, while `rolling('7D')` reports from the first row because its default is 1. Set `min_periods` explicitly on both to make the edges match.
rolling(7) is "the last seven receipts in the drawer", however old they are; rolling('7D') is "every receipt dated in the past week", however many that is.
- rolling(7) on daily data always covers seven calendar days
- rolling('7D') fills missing dates with NaN before averaging
- Both window forms default min_periods to the window size
- Offset windows work on an unsorted index
- center=True only works for integer windows