Sub topic 3
Controlling the edges with min_periods
This chapter assumes you can create a pandas Series, you know rolling(window) from the previous chapter, and you are comfortable with NaN as pandas' missing-value marker. Here you will learn why rolling results start with NaN and how min_periods changes that.
Why the first rows are NaN
A rolling window of size 3 needs three values before it can produce a result. At row 0 only one value exists, so pandas returns NaN instead of averaging a partial window.
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 rule behind this is min_periods, the minimum number of non-missing observations a window must contain before pandas computes a result. For an integer window, the default is equal to the window size. So rolling(3) means rolling(3, min_periods=3).
Lowering min_periods
If you accept results from partial windows, set a smaller min_periods.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(window=3, min_periods=1).mean())
# 0 1.0
# 1 1.5
# 2 2.0
# 3 3.0
# 4 4.0
# 5 5.0Row 0 now averages one value, and row 1 averages two. From row 2 onward the windows are full and the output is the same as before.
The leading values are less reliable than the rest. A mean of one value is just that value, and a standard deviation of one value is undefined. Choose min_periods according to how much evidence you need for the statistic to mean something.
The value must also be at least 1 and no larger than the window. A larger value raises a ValueError, because the window could never hold enough values.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
try:
s.rolling(window=3, min_periods=4).mean()
except ValueError as err:
print(err)
# min_periods 4 must be <= window 3min_periods also counts missing data
min_periods counts non-missing values inside the window, not rows. A window can be full-sized and still produce NaN if it contains too many gaps. This is a common source of unexpected NaN values in the middle of a result.
import numpy as np
import pandas as pd
s = pd.Series([1, np.nan, 3, 4, 5])
print(s.rolling(window=3).mean())
# 0 NaN
# 1 NaN
# 2 NaN
# 3 NaN
# 4 4.0
print(s.rolling(window=3, min_periods=2).mean())
# 0 NaN
# 1 NaN
# 2 2.0
# 3 3.5
# 4 4.0With the default, rows 2 and 3 are NaN because each window holds only two real values. With min_periods=2, those windows qualify. Row 2 averages 1 and 3, and row 3 averages 3 and 4.
The decision pandas makes for each row looks like this:
Defaults differ by window type
The default of min_periods depends on how you define the window:
| Window | Default min_periods |
|---|---|
| Integer, such as `rolling(3)` | Window size (3) |
| Time offset, such as `rolling("3D")` | 1 |
| `expanding()` | 1 |
A time-based window has no fixed row count, so requiring a full window would not make sense. Expanding windows start at one row by design. Both are covered in later chapters.
Choosing a value
- Keep the default when every output must come from a full window, for example when comparing windows of equal size.
- Use
min_periods=1when you want a value from the first row and accept noisy early results. - Use an intermediate value, such as half the window, to require some evidence without dropping the first rows entirely.
- Raise
min_periodsabove the window's expected share of gaps if your data has many missing values and you want those rows to stayNaN.
Exercise
What does pd.Series([2, np.nan, np.nan, 8, 10]).rolling(window=3, min_periods=2).mean() return for each row?
Show answer
Only the last row has a value. The first four rows are NaN, because each of their windows holds at most one non-missing number. The last window is [NaN, 8, 10], which holds two non-missing values, so the result is 9.0.
Exercise
A rolling mean with window=5 and the default min_periods returns NaN at row 7, even though rows 3 to 7 all exist. What is the likely cause, and how can you allow a result?
Show answer
At least one of the five values in that window is NaN, so the count of non-missing values is below 5, the default minperiods. Lower minperiods, for example to 3, so the window qualifies when enough real values are present.