Sub topic 6
Time-based windows on a DatetimeIndex
This chapter assumes you can build a Series or DataFrame with a DatetimeIndex, and that you know the fixed-size rolling(window) call from earlier chapters, including min_periods and NaN at the edges. You should also be comfortable with sum, mean and count.
A fixed-size window such as rolling(3) counts rows. A time-based window counts elapsed time. The question changes from "the last 3 rows" to "everything in the last 3 days". The two answers match only when the rows are evenly spaced and complete.
Why row counts are not enough
Real data is often irregular. A sensor reports when it has something to say, a store is closed on Sundays, and a log has bursts and silences. For irregular data, rolling(3) quietly changes meaning from row to row. One window might span three minutes and the next three weeks.
A time-based window fixes the span and lets the number of rows vary. To get one, pass an offset string such as "3D", "12h" or "90min" instead of an integer.
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
df = pd.DataFrame({"sales": [10, 20, 30, 40]}, index=idx)
df["rows_3"] = df["sales"].rolling(3).sum()
df["days_3d"] = df["sales"].rolling("3D").sum()
print(df)
# sales rows_3 days_3d
# 2024-01-01 10 NaN 10.0
# 2024-01-02 20 NaN 30.0
# 2024-01-04 30 60.0 50.0
# 2024-01-07 40 90.0 40.0The rows_3 column is NaN for the first two rows, and then each value spans three rows however far apart they are. The days_3d column has a value from the first row, and the number of rows behind each value changes.
How the window is defined
For each timestamp t, a "3D" window covers the interval (t - 3 days, t]. This interval has two properties.
- The right edge is closed, so the current row is always included.
- The left edge is open, so a row exactly 3 days earlier is excluded.
Check this against the 2024-01-04 row. The window is (2024-01-01, 2024-01-04]. The January 1 row sits exactly on the open edge and drops out. That leaves January 2 and January 4, so the sum is 20 + 30 = 50. For January 7 the window is (2024-01-04, 2024-01-07], which holds only the row for January 7, so the sum is 40.
You can see how many rows each window contains with count:
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
s = pd.Series([10, 20, 30, 40], index=idx)
print(s.rolling("3D").count())
# 2024-01-01 1.0
# 2024-01-02 2.0
# 2024-01-04 2.0
# 2024-01-07 1.0
# dtype: float64Use this check whenever a time-based result looks surprising. It shows the real window sizes.
Controlling which edges are included
The closed argument sets which edges of the interval are included. It accepts "right" (the default), "left", "both" and "neither".
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
s = pd.Series([10, 20, 30, 40], index=idx)
out = pd.DataFrame(
{c: s.rolling("3D", closed=c).sum() for c in ["right", "left", "both", "neither"]}
)
print(out)
# right left both neither
# 2024-01-01 10.0 NaN 10.0 NaN
# 2024-01-02 30.0 10.0 30.0 10.0
# 2024-01-04 50.0 30.0 60.0 20.0
# 2024-01-07 40.0 30.0 70.0 NaNThe meaning of each option is:
| `closed` | Interval | Includes current row | Typical use |
|---|---|---|---|
| `"right"` | `(t - w, t]` | Yes | Default; the usual "last w of time" statistic |
| `"left"` | `[t - w, t)` | No | Features that must not see the current row |
| `"both"` | `[t - w, t]` | Yes | Windows where a row exactly `w` earlier still counts |
| `"neither"` | `(t - w, t)` | No | Strict exclusion at both ends |
With closed="left" and closed="neither" the current row is not in its own window. The first row then has an empty window, which is why the result is NaN. This is a handy way to build look-behind features without a separate shift. The later chapter on leakage covers that.
min_periods behaves differently here
For integer windows, min_periods defaults to the window size. For offset windows it defaults to 1. This is why rolling("3D") produced a number in the very first row while rolling(3) did not.
The default is easy to forget, and it means early rows are computed from very little data. A "7D" mean at the first timestamp is just that one value. To demand more evidence, set min_periods yourself:
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
s = pd.Series([10, 20, 30, 40], index=idx)
print(s.rolling("3D", min_periods=2).sum())
# 2024-01-01 NaN
# 2024-01-02 30.0
# 2024-01-04 50.0
# 2024-01-07 NaN
# dtype: float64min_periods counts valid observations, so a NaN value inside the window does not count toward it. The last row is NaN because only one observation falls in its window. That is the correct signal when data has gone quiet. A fixed-size window would instead have reached back to older rows.
Where the timestamps come from
The index does not have to be the time axis. If the timestamps are in a column, name it with on:
import pandas as pd
df = pd.DataFrame({
"date": pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"]),
"sales": [10, 20, 30, 40],
})
df["sales_3d"] = df.rolling("3D", on="date")["sales"].sum()
print(df)
# date sales sales_3d
# 0 2024-01-01 10 10.0
# 1 2024-01-02 20 30.0
# 2 2024-01-04 30 50.0
# 3 2024-01-07 40 40.0The result keeps the original integer index, so assigning it back aligns row for row. The on column is not itself aggregated. Select the columns you want after rolling(...), as above.
Requirements and common errors
Time-based windows have requirements that integer windows do not. Each requirement has a matching error.
- The time axis must be sorted. If the index or
oncolumn is not monotonic, pandas raises aValueErrorthat mentions "monotonic". Callsort_index()first, orsort_values("date")when usingon. Duplicate timestamps are allowed as long as the order never goes backwards. - The time axis must be datetime-like. An offset string on a
RangeIndexor a column of strings raisesValueError. Convert withpd.to_datetimefirst. - The offset must be a fixed duration. Units with a variable length, such as
"1M"(a month) or"1Y"(a year), raise aValueErrorabout a non-fixed frequency. Use"30D"or"365D"to say what you mean. For calendar months, aggregate withresample. - Missing timestamps are not filled in. A time-based window shrinks around gaps but does not create rows. If you want a result for every day, call
asfreq("D")orreindexfirst, then roll.
A frequent mistake is to sort after computing the rolling result. The sort must come before the rolling call, because the result depends on row order.
import pandas as pd
idx = pd.to_datetime(["2024-01-04", "2024-01-01", "2024-01-02"])
s = pd.Series([30, 10, 20], index=idx)
result = s.sort_index().rolling("3D").sum()
print(result)
# 2024-01-01 10.0
# 2024-01-02 30.0
# 2024-01-04 50.0
# dtype: float64Rolling versus resample
Both tools group data by time, but they answer different questions. resample("3D") cuts the timeline into separate 3-day bins and returns one value per bin. rolling("3D") slides a 3-day window along and returns one value per original row, so consecutive windows overlap.
| Tool | Output rows | Windows overlap | Use for |
|---|---|---|---|
| `rolling(3)` | One per input row | Yes | Evenly spaced data, row-based smoothing |
| `rolling("3D")` | One per input row | Yes | Irregular data, "last 3 days" statistics |
| `resample("3D")` | One per time bin | No | Reporting totals per period |
If you need a rolling statistic at regular dates but your data is irregular, there are two steps. First resample or asfreq to a regular grid, then roll over that grid. Alternatively, roll first and then sample the result at the dates you want. The two orders give different numbers, so pick the one that matches how the metric is defined.
Several aggregations at once
Time-based windows support the same built-in aggregations as integer windows, including agg with a list. The windows are computed once and each aggregation is applied to them.
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
s = pd.Series([10, 20, 30, 40], index=idx)
print(s.rolling("3D").agg(["mean", "min", "max", "count"]))Pair a statistic with count when the window size varies. A mean over one row and a mean over six rows are not equally trustworthy, and count makes that visible. A common pattern is to compute the statistic, then mask it where count is below a threshold. That is the same effect as min_periods, but it keeps the information for later inspection.
Edge cases to keep in mind
- Time zones. With a tz-aware index,
"1D"is treated as a fixed 24 hours of elapsed time, so a window that crosses a daylight-saving change can hold a different local wall-clock span. Check this if your reports are in local time. - Centered windows. The
centerargument also works with offset windows in recent pandas versions (1.3 and later). Check your installed version before relying on it. For a look-behind feature, avoid it, because it uses future rows. - Very long gaps. A gap longer than the window leaves a window holding only the current row. With the default
min_periods=1the statistic silently restarts. Raisemin_periodsif that matters. - Integer windows on a DatetimeIndex.
rolling(3)on a datetime-indexed Series still counts rows. Only a string or offset object triggers time-based behavior.
Exercises
Exercise
Using the data below, what does s.rolling("2D").sum() return? Work it out by hand from the interval (t - 2 days, t], then explain why the January 4 value does not include the January 2 row.
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
s = pd.Series([10, 20, 30, 40], index=idx)
Show answer
The result is 10, 30, 30, 40. January 1: the window is (Dec 30, Jan 1], so only 10. January 2: (Dec 31, Jan 2] holds 10 and 20, giving 30. January 4: (Jan 2, Jan 4] holds only 30, because January 2 sits exactly 2 days earlier and the left edge is open. January 7: (Jan 5, Jan 7] holds only 40. Using closed="both" would add the January 2 row back into the January 4 value, giving 50.
Exercise
A colleague writes s.rolling("1M").mean() to get a monthly moving average and gets a ValueError. Why does it fail, and what are two ways to fix it, depending on what they actually want?
Show answer
A month has no fixed length, so it is not a valid window duration and pandas raises a ValueError about a non-fixed frequency. If a 30-day moving average is acceptable, use s.rolling("30D").mean(). If they want one average per calendar month, use s.resample("MS").mean() (or "ME" in newer pandas), which creates calendar bins instead of a sliding window.