Sub topic 6
Time-based windows on a DatetimeIndex
This chapter assumes you know how to build a pandas Series or DataFrame, use a DatetimeIndex, and read basic statistics such as mean and sum. You should also have seen fixed-size rolling(window) from earlier chapters.
Row counts versus time spans
A fixed window such as rolling(3) always uses three rows. That works when rows are evenly spaced. Real data often has gaps: missing days, irregular sensor readings, or orders that arrive at random moments. Three rows can then cover one day or three weeks.
A time-based window fixes the span of time instead. You pass an offset string such as "3D" (3 days) or "2h" (2 hours). The number of rows in each window then depends on the data.
The basic form
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["sales_3d"] = df["sales"].rolling("3D").sum()
print(df)
# sales sales_3d
# 2024-01-01 10 10.0
# 2024-01-02 20 30.0
# 2024-01-04 30 50.0
# 2024-01-07 40 40.0For each timestamp t, pandas uses every row in the interval (t - 3 days, t]. The start is excluded and the end is included. Take the row for January 4:
- The interval is (January 1, January 4].
- January 1 is excluded.
- January 2 and January 4 remain, so the sum is 20 + 30 = 50.
What changes compared with fixed windows
Three differences matter in practice.
- The row count varies. Use
count()to see how many rows each window held. min_periodsdefaults to 1. A fixed window returnsNaNuntil it is full. A time window returns a result as soon as one row falls inside it, so you rarely see leadingNaNvalues.- The index must be sorted. The index has to be monotonic (increasing or decreasing). Otherwise pandas raises a
ValueError.
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)
print(df["sales"].rolling("3D").count())
# 2024-01-01 1.0
# 2024-01-02 2.0
# 2024-01-04 2.0
# 2024-01-07 1.0
# Name: sales, dtype: float64If you want results only from windows with enough data, set min_periods explicitly. For example, rolling("3D", min_periods=2) returns NaN for January 1 and January 7 in the data above.
Using a column instead of the index
If the timestamps are in a column, pass it with on. The column must still be sorted.
import pandas as pd
df = pd.DataFrame({
"when": pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"]),
"sales": [10, 20, 30, 40],
})
print(df.rolling("3D", on="when")["sales"].sum())Controlling the interval with closed
The closed argument decides which ends of the interval are included. For time windows the default is "right", which gives (t - 3D, t]. Use closed="left" to get [t - 3D, t), which leaves out the current row. This is useful when a row should be described only by earlier rows.
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", closed="left").sum())
# 2024-01-01 NaN
# 2024-01-02 10.0
# 2024-01-04 30.0
# 2024-01-07 30.0
# dtype: float64The first result is NaN because its window holds no rows. The other options are "both" and "neither".
Common errors
Two other mistakes are worth checking for:
- Using an integer where you meant a time span.
rolling(3)means three rows, androlling("3D")means three days. - Forgetting that the current row is inside the window by default. If you build features for prediction, shift the result or use
closed="left". A later chapter covers this look-ahead problem.
Exercise
Using the same four-row sales data (January 1, 2, 4 and 7 with sales 10, 20, 30, 40), what does rolling("2D").sum() return for each row?
Show answer
10, 30, 30, 40. Each window covers (t - 2 days, t]. January 1 has only itself (10). January 2 includes January 1 and 2 (10 + 20 = 30). January 4 excludes January 2 because the interval starts after January 2, so only January 4 remains (30). January 7 has only itself (40).