Sub topic 5
Window alignment with center and closed
This chapter assumes you know how rolling(window) works and how min_periods affects the leading NaN values. It also assumes you can build a DataFrame with a DatetimeIndex. Here you will control which rows each window covers relative to the current row.
The default window is trailing
By default, the window for row i ends at row i. It includes the current row and the rows before it. This is why a 3-row rolling mean starts with two NaN values: the first two rows don't have enough history.
Two options change the alignment:
centermoves the window so the current row sits in the middle.closeddecides whether each end of the window includes its boundary point.
Centering with `center=True`
With center=True, a 3-row window covers the previous row, the current row, and the next row. The NaN values then appear at both ends of the result.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
out = pd.DataFrame({
"value": s,
"trailing": s.rolling(3).mean(),
"centered": s.rolling(3, center=True).mean(),
})
print(out)
# value trailing centered
# 0 1 NaN NaN
# 1 2 NaN 2.0
# 2 3 2.0 3.0
# 3 4 3.0 4.0
# 4 5 4.0 5.0
# 5 6 5.0 NaNThe centered value at row 2 is the mean of rows 1, 2 and 3. The trailing value at row 2 is the mean of rows 0, 1 and 2. A centered window smooths a series without shifting its peaks later in time, which makes it a good fit for plotting and for describing past data.
Centering also works with time-based windows in recent pandas versions (1.3 and later). With an even window size, the current row can't sit exactly in the middle, so one side gets an extra row.
Choosing which edges count with `closed`
Time-based windows have two boundaries: a start at t - window and an end at t. The closed argument sets which of those boundaries is included.
| `closed` value | Interval for a `3D` window | Includes start | Includes end |
|---|---|---|---|
| `"right"` (default) | `(t - 3D, t]` | No | Yes |
| `"left"` | `[t - 3D, t)` | Yes | No |
| `"both"` | `[t - 3D, t]` | Yes | Yes |
| `"neither"` | `(t - 3D, t)` | No | No |
The next example runs all four options on irregularly spaced dates.
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
sales = pd.Series([10, 20, 30, 40], index=idx)
out = pd.DataFrame({
c: sales.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 NaNLook at 2024-01-04. The window start is 2024-01-01, which is exactly three days earlier.
- With
"right", the start is excluded, so the window holds only January 2 and 4: 20 + 30 = 50. - With
"both", January 1 is included, so the sum is 10 + 20 + 30 = 60. - With
"left", the current row is excluded and January 1 is included, so the sum is 10 + 20 = 30.
The NaN values for "left" and "neither" on January 1 appear because the window is empty. The current row is excluded and no earlier rows exist.
Choosing between the options
- Use the default trailing window for reporting that follows time, such as a 7-day moving average on a dashboard.
- Use
center=Truefor smoothing and visual inspection of historical data. - Use
closed="left"orclosed="neither"when the window should describe the past only. - Use
closed="both"rarely. It can make a window one step longer than you expect, because both ends are included.
Rolling windows with an integer size also accept closed in pandas 1.2 and later. Check your installed version with pd.__version__ if the argument raises an error.
Common errors
- Assuming
closedchanges the number of rows in a fixed-size window. It shifts which rows are used, but the row count stays fixed. In a time-based window, the row count varies with the data. - Forgetting that
closed="left"andclosed="neither"can produce empty windows, so the first result isNaN. - Passing
center=Trueand then using the result as a model feature.
Exercise
Using the sales data above (10, 20, 30, 40 on 2024-01-01, 01-02, 01-04, 01-07), what does rolling("3D", closed="both").sum() return for 2024-01-07, and why does it differ from the default closed="right" result of 40?
Show answer
It returns 70. With closed="both" the window is [2024-01-04, 2024-01-07], so it includes the January 4 row (30) as well as the January 7 row (40). With the default closed="right" the window is (2024-01-04, 2024-01-07], which excludes January 4, so only 40 remains.