Sub topic 5
Window alignment with center and closed
This chapter assumes you can build a Series with a DatetimeIndex and that you know the basics of rolling(window) and min_periods. Both options here change which rows each window contains. They don't change the aggregation. If you pick the wrong alignment, the numbers still look plausible, and that is why this chapter exists.
What alignment means
A rolling calculation produces one result per row. Alignment answers two questions. Which rows go into the window for row i? And which edges of the window, the first row and the last row, are included?
By default, pandas uses a trailing window. The window for row i ends at row i, and the result is labeled with that row. With window=3, row 3 uses rows 1, 2 and 3. The calculation never looks at later rows, so the result at row 3 can be known at row 3.
Two parameters change this:
centermoves the window so that it surrounds rowiinstead of trailing it.closeddecides whether the window's two boundary points are included.
Centering a window with center=True
A trailing mean reacts late to changes. To see this, smooth a series that jumps from 0 to 10.
import pandas as pd
s = pd.Series([0, 0, 0, 10, 10, 10])
out = pd.DataFrame({
"raw": s,
"trailing": s.rolling(3).mean(),
"centered": s.rolling(3, center=True).mean(),
}).round(2)
print(out)
# raw trailing centered
# 0 0 NaN NaN
# 1 0 NaN 0.00
# 2 0 0.00 3.33
# 3 10 3.33 6.67
# 4 10 6.67 10.00
# 5 10 10.00 NaNThe raw jump happens at row 3. The trailing mean reaches 10 at row 5, two rows later, because the window needs to fill with new values. The centered mean reaches 10 at row 4. It is also symmetric around the jump, which is what you want when you draw a smoothed line over the data.
Centering also moves the NaN values. With a trailing window they all sit at the start. With center=True and the default min_periods, they are split between the start and the end, because the last rows have no later neighbours.
Even window sizes are asymmetric
An odd window has a middle row. An even window does not, so pandas has to choose. It places the extra row on the earlier side.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(4, center=True).mean())
# 0 NaN
# 1 NaN
# 2 2.5
# 3 3.5
# 4 4.5
# 5 NaNFor row 3, the window holds rows 1, 2, 3 and 4: two rows behind the current row and one ahead. The result at row 2 is the mean of rows 0 to 3. That is two NaN values at the start and one at the end. If you need exact symmetry, use an odd window.
Centering is not the same as shifting
For an odd window, a centered result equals a trailing result shifted backward. For window 3, s.rolling(3, center=True).mean() matches s.rolling(3).mean().shift(-1). The two differ once you lower min_periods. With min_periods=1, the centered version still returns a value on the last row, using the rows that exist. The shifted version returns NaN there, because the shift pushes in an empty slot. Use center=True when you want pandas to handle the edges. Use shift when you want explicit control over labels.
Which rows are included: closed
A window has a start boundary and an end boundary. The closed parameter decides which of them belong to the window. It accepts four values:
| Value | Start boundary | End boundary |
|---|---|---|
| `"right"` | excluded | included |
| `"left"` | included | excluded |
| `"both"` | included | included |
| `"neither"` | excluded | excluded |
The default is "right". This is why a trailing window includes the current row: the current row is the right boundary.
Fixed-size windows
For integer windows, closed works in pandas 1.2 and later. Older versions raise a ValueError saying it is only implemented for datetime-like and offset-based windows. For a window of 3, the rows in the window for position 3 are:
| Setting | Rows used for position 3 |
|---|---|
| default (`"right"`) | 1, 2, 3 |
| `center=True` | 2, 3, 4 |
| `closed="left"` | 0, 1, 2 |
| `closed="both"` | 0, 1, 2, 3 |
| `closed="neither"` | 1, 2 |
"left" keeps three rows but moves them back so that the current row is excluded. "both" adds a fourth row. "neither" drops to two rows.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(3, closed="left").mean())
# 0 NaN
# 1 NaN
# 2 NaN
# 3 2.0
# 4 3.0
# 5 4.0Row 3 averages rows 0, 1 and 2, which are 1, 2 and 3. Row 2 is NaN because only rows 0 and 1 are available, and the default min_periods is 3. With min_periods=1, rows 1 to 5 would also have values, and only row 0 would stay NaN because its window is empty.
Time-based windows
With a string window such as "3D", the boundaries are timestamps, so closed decides whether a row that falls exactly on a boundary is counted. This is where the option matters most. Compare all four settings on one daily series.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=5, freq="D")
sales = pd.Series([1, 2, 3, 4, 5], 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 1.0 NaN 1.0 NaN
# 2024-01-02 3.0 1.0 3.0 1.0
# 2024-01-03 6.0 3.0 6.0 3.0
# 2024-01-04 9.0 6.0 10.0 5.0
# 2024-01-05 12.0 9.0 14.0 7.0Read the January 4 row. The window spans from January 1 to January 4.
"right"covers (Jan 1, Jan 4], so it counts Jan 2, 3 and 4: 2 + 3 + 4 = 9."left"covers [Jan 1, Jan 4), so it counts Jan 1, 2 and 3: 1 + 2 + 3 = 6."both"covers [Jan 1, Jan 4], so it counts all four days: 10."neither"covers (Jan 1, Jan 4), so it counts Jan 2 and 3: 5.
Two edge cases follow from this:
- A time-based window can be empty.
"left"and"neither"returnNaNon January 1 because no earlier row exists. Time-based windows usemin_periods=1by default, so a window with one row returns a value, and only an empty window returnsNaN. center=Truealso works with time-based windows in pandas 1.3 and later. Earlier versions raise an error.
Excluding the current row
The most common practical use of closed is to build a feature from earlier rows only. For a fixed window, closed="left" gives the same values as shifting the trailing result by one row.
import pandas as pd
df = pd.DataFrame({"sales": [10, 20, 30, 40, 50, 60]})
a = df["sales"].rolling(3, closed="left").mean()
b = df["sales"].rolling(3).mean().shift(1)
print(a.equals(b))
# TrueFor time-based windows the two approaches can disagree, and closed="left" is the more reliable one. shift(1) moves by one row, regardless of how much time that row represents. If your index has gaps or duplicate timestamps, the previous row may be far away or may share the current timestamp. closed="left" excludes by timestamp, so every row at the current time is left out.
Common errors
- Using
center=Truefor a model feature. The feature contains future data, and the model's score on historical data will be better than it can ever be live. - Expecting a symmetric even window. pandas puts the extra row before the current row. Use an odd window if symmetry matters.
- Forgetting
closedon a time window. On regular data, the default"right"yields windows of exactly three rows for"3D"."both"yields four. If you copy a setting between a fixed window and a time window, the row counts change. - Using
closedwith an old pandas. Fixed-sizeclosedneeds 1.2, and time-basedcenterneeds 1.3. Checkpd.__version__when a call raisesValueError. - Reading
NaNas a bug. Alignment changes where the leading and trailingNaNvalues fall. Usemin_periodsto control them, as described earlier in this tutorial.
Exercise
You have a daily DataFrame df with a DatetimeIndex and a price column. You want a 7-day mean of earlier prices to use as a model feature, and the feature at each date must not include that date's own price. Write the expression, and explain why closed="left" is safer than shift(1) if the index has missing days.
Show answer
Use df["price"].rolling("7D", closed="left").mean(). The window for each date covers [t - 7 days, t), so the current row is excluded. shift(1) moves values by one row, not by one day. If days are missing, the previous row may be several days earlier, so the feature would no longer describe the same time span. closed="left" uses timestamps, so the span stays correct.
Exercise
For s = pd.Series([1, 2, 3, 4, 5, 6]), which rows does s.rolling(4, center=True) use to compute the result at position 3, and which positions are NaN with the default min_periods?
Show answer
It uses rows 1, 2, 3 and 4 (values 2, 3, 4, 5, mean 3.5). The window has two rows behind the current row and one ahead, because pandas puts the extra row of an even window on the earlier side. Positions 0, 1 and 5 are NaN, because their windows hold fewer than 4 rows.