Sub topic 2
Fixed-size rolling windows
This chapter assumes you can create and index a pandas Series and DataFrame, and that you know basic descriptive statistics such as mean, sum and standard deviation. You do not need a DatetimeIndex here. Time-based windows come in a later chapter.
What a fixed-size rolling window does
A fixed-size rolling window looks at a set number of consecutive rows at a time. For each row, pandas takes that row and the rows before it, up to the window size, and computes one statistic over them. Then the window moves down by one row and repeats.
You create the window with rolling(window=n). This returns a Rolling object. It holds no result yet. It is a description of the windows. The result appears when you call an aggregation such as mean() on it.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(window=3).mean())
# 0 NaN
# 1 NaN
# 2 2.0
# 3 3.0
# 4 4.0
# 5 5.0The output has the same length and the same index as the input. This is the main difference from a groupby aggregation, which collapses many rows into one. A rolling calculation returns one value per input row.
The windows overlap. Row 2 uses rows 0, 1 and 2. Row 3 uses rows 1, 2 and 3. Each row is therefore used in up to three different windows.
Why the first rows are NaN
The first two results in the example are NaN. A window of size 3 needs three values, and rows 0 and 1 do not have three values available. By default pandas requires a full window, so it returns NaN for any row where the window is incomplete.
The number of leading NaN values is window - 1. With window=3 you get two. With window=30 you get 29. If you use a large window on a short series, most of the output can be NaN.
The next chapter covers min_periods, which relaxes this rule. For now, remember that NaN at the start is expected behavior and not an error.
The window includes the current row
The default window is trailing. It ends at the current row and extends backward. In the example above, the value at row 3 is the mean of rows 1, 2 and 3, which is (2 + 3 + 4) / 3 = 3.0.
This matters when you build features for a model. A trailing window that includes the current row uses the current value. If you are predicting that value, the feature has already seen the answer. A later chapter on look-ahead leakage shows how to handle this. For now, keep in mind that "rolling mean at row t" means "mean of rows t − window + 1 through t".
Window size is a number of rows
For an integer window, the size counts rows, not time. pandas does not look at the index values. If your data has gaps, such as missing days, a window of 7 still means seven rows. Those seven rows may span more than seven days.
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-05", "2024-01-20"])
s = pd.Series([1, 2, 3, 4], index=idx)
print(s.rolling(window=2).mean())The result at 2024-01-20 averages the values from 2024-01-05 and 2024-01-20, which are fifteen days apart. If you need windows defined by elapsed time, use a string window such as "7D". That is the subject of a later chapter.
Rolling on a DataFrame
On a DataFrame, rolling applies the same window to each numeric column independently.
import pandas as pd
df = pd.DataFrame({
"a": [1, 2, 3, 4, 5],
"b": [10, 20, 30, 40, 50],
})
print(df.rolling(window=3).mean())
# a b
# 0 NaN NaN
# 1 NaN NaN
# 2 2.0 20.0
# 3 3.0 30.0
# 4 4.0 40.0Columns do not influence each other in a simple aggregation like mean. Column a is only averaged with other values from column a. If you want to roll over one column only, select it first with df["a"].rolling(3).mean().
Some methods do combine columns. corr and cov can compute a rolling relationship between two series, for example df["a"].rolling(3).corr(df["b"]). These are the exception.
Window sizes that are valid
The window argument must be a positive integer for a fixed window. These cases raise errors or give surprising results:
window=0or a negative number raises aValueError.- A window larger than the series length is allowed. With the default
min_periods, every result isNaN, because no window is ever full. - A float such as
3.5raises an error. Use an integer.
import pandas as pd
s = pd.Series([1, 2, 3])
print(s.rolling(window=5).mean())
# 0 NaN
# 1 NaN
# 2 NaNIf you see a column full of NaN after a rolling call, compare the window size to the number of rows first. This is the most common cause.
Missing values inside the data
NaN values in your data also affect rolling results. With the default settings, a window that contains any NaN produces NaN, because the window does not have enough valid observations.
import pandas as pd
s = pd.Series([1, 2, None, 4, 5, 6])
print(s.rolling(window=3).mean())
# 0 NaN
# 1 NaN
# 2 NaN
# 3 NaN
# 4 NaN
# 5 5.0The default requires window valid values in each window. The NaN at row 2 spoils the windows ending at rows 2, 3 and 4. Only the window ending at row 5 (rows 3, 4 and 5) is complete. The min_periods argument lets you accept windows with fewer valid values. That is the first thing to reach for when your data has gaps.
Note that this is not the same as the leading NaN from an incomplete window. Both come from the same rule, which is that the count of valid values in the window must reach min_periods.
Result position and the index
The result at each row is labeled with the index label of the last row in the window. You can see this by comparing the input and output indexes. They are identical.
This labeling is why you can assign the result straight back into a DataFrame:
import pandas as pd
df = pd.DataFrame({"price": [100, 102, 101, 105, 107, 110]})
df["ma3"] = df["price"].rolling(window=3).mean()
print(df)
# price ma3
# 0 100 NaN
# 1 102 NaN
# 2 101 101.000000
# 3 105 102.666667
# 4 107 104.333333
# 5 110 107.333333Assignment aligns on the index, so each moving average lands next to the price it was computed at. If your index has duplicates or is unsorted, be careful. Rolling uses row order, not index order. Sort first when order matters.
import pandas as pd
df = pd.DataFrame(
{"price": [105, 100, 102]},
index=[3, 1, 2],
)
df = df.sort_index()
print(df["price"].rolling(2).mean())Common errors
- Reading
NaNas a bug. The firstwindow - 1values areNaNby design. - Forgetting the aggregation.
s.rolling(3)alone prints aRolling [window=3,center=False,axis=0,method=single]description, not numbers. Add.mean()or another method. - Assuming rows are time. An integer window counts rows. Gaps in time are invisible to it.
- Rolling over unsorted data. The window follows row order. Sort by time before you roll.
- Using a window larger than the data. Every output is
NaN.
Quick check
Try the exercises below before moving on. They use only what this chapter covered.
Exercise
A Series has 100 rows and you call s.rolling(window=10).mean() with default settings and no missing data. How many NaN values appear in the result, and at which positions?
Show answer
There are 9 NaN values, at positions 0 through 8. A full window needs 10 rows, so the first full window ends at position 9. In general the count is window - 1.
Exercise
Given s = pd.Series([2, 4, 6, 8]), what does s.rolling(window=2).sum() return?
Show answer
It returns NaN, 6.0, 10.0, 14.0. Position 0 has only one row, so it is NaN. Position 1 sums 2 + 4 = 6. Position 2 sums 4 + 6 = 10. Position 3 sums 6 + 8 = 14.
Exercise
A daily sales Series is missing the weekend days, so it has five rows per week. Why does rolling(window=7).mean() not give a true 7-day average, and what kind of window fixes this?
Show answer
An integer window counts rows, not calendar days. Seven rows here cover about 9 or 10 calendar days. A time-based window such as rolling("7D") on a DatetimeIndex covers exactly seven calendar days regardless of how many rows fall inside.