Sub topic 2
Fixed-size rolling windows
This chapter assumes you can create pandas Series and DataFrames, know basic statistics such as mean and sum, and have read the chapter on what a window calculation is. Here you compute a statistic over a window of a fixed number of rows and learn to read the NaN values at the start of the result.
The idea
rolling(window=n) builds a window that is n rows long. For each row, the window covers that row and the n - 1 rows before it. You then call an aggregation such as mean() on it, and pandas moves the window down one row at a time.
A first example
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.0
# dtype: float64Row 2 holds the mean of rows 0, 1 and 2, which is (1 + 2 + 3) / 3 = 2.0. Row 3 holds the mean of 2, 3 and 4, which is 3.0.
Two things to notice:
- The result has the same index and length as the input. Each result is labeled with the last row of its window.
- The first two results are
NaN. At rows 0 and 1, fewer than three values are available, and by default pandas returns a result only for a full window.
The call s.rolling(3) alone does not compute anything. It returns a Rolling object that describes the window. The calculation happens when you call an aggregation on it.
Rolling over a DataFrame
On a DataFrame, the window slides down each column separately.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [10, 20, 30, 40]})
print(df.rolling(2).sum())
# a b
# 0 NaN NaN
# 1 3.0 30.0
# 2 5.0 50.0
# 3 7.0 70.0Results are floats because NaN is a float value. Integer input still produces float output.
Reading the leading NaN values
With a window of n rows, the first n - 1 results are NaN. You can find the first valid row with this rule: the first full window ends at position n - 1, counting from zero.
Missing values inside the data
By default a window needs a full set of non-missing values. One NaN inside the window makes that result NaN, so a single gap spreads across several output rows.
import numpy as np
import pandas as pd
s = pd.Series([1, np.nan, 3, 4, 5])
print(s.rolling(2).mean())
# 0 NaN
# 1 NaN
# 2 NaN
# 3 3.5
# 4 4.5
# dtype: float64Rows 1 and 2 are NaN because each of their windows contains the missing value. The next chapter shows how to relax this requirement.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| The output prints something like `Rolling [window=3,...]` | You did not call an aggregation | Add `.mean()`, `.sum()` or another method |
| Every result is `NaN` | The window is larger than the number of rows, or every window contains a missing value | Check `len(s)` and look for gaps in the data |
| The window seems to be one row too long or too short | You counted the window as excluding the current row | The current row is always included |
| Results look shifted compared with a centered average | The default window trails the current row | Align the window differently, as covered in a later chapter |
Choosing a window size
A larger window gives a smoother result that reacts more slowly to changes. A smaller window follows the data closely but is noisier. For daily data, a window of 7 gives a weekly view, and a window of 30 gives a monthly view. Pick the size from what you want the statistic to represent, not from the data length.
Exercise
Given s = pd.Series([2, 4, 6, 8, 10]), what does s.rolling(4).sum() return?
Show answer
The first three values are NaN because fewer than four rows are available. Row 3 is 2 + 4 + 6 + 8 = 20.0, and row 4 is 4 + 6 + 8 + 10 = 28.0. The result is NaN, NaN, NaN, 20.0, 28.0.
Exercise
Why is the output of pd.Series([1, 2, 3]).rolling(3).mean() not [1.0, 1.5, 2.0], and which setting would change that?
Show answer
By default a result needs a full window of 3 values, so only the last row has one. The output is NaN, NaN, 2.0. Lowering min_periods, for example to 1, allows partial windows at the start.