Sub topic 3
Controlling the edges with min_periods
This chapter assumes you know basic Python, how to build pandas Series and DataFrames, and how rolling(window).mean() works. The previous chapter showed that a fixed-size rolling window returns NaN for the first rows. Here you will learn why that happens, how to change it with min_periods, and when changing it is a bad idea.
What min_periods means
min_periods is the minimum number of valid observations a window must contain before pandas computes a result. A valid observation is a value that is not NaN. If the window has fewer valid observations than min_periods, the result for that row is NaN.
The defaults differ by window type:
| Window type | Default min_periods |
|---|---|
| Fixed-size rolling, such as `rolling(3)` | Equal to `window` |
| Time-based rolling, such as `rolling("3D")` | 1 |
| `expanding()` | 1 |
The first row of the table explains the leading NaN values you saw earlier. With window=3, the first two rows can never hold three observations, so they are NaN.
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.0Lowering min_periods
Set min_periods to a smaller number to accept partial windows at the start of the data.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(window=3, min_periods=2).mean())
# 0 NaN
# 1 1.5
# 2 2.0
# 3 3.0
# 4 4.0
# 5 5.0Row 1 now averages the two values it has, 1 and 2. Row 0 has only one value, so it stays NaN. With min_periods=1, even row 0 gets a result, and the leading NaN values disappear completely.
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.0Rows 0 and 1 are averages over fewer than three values, so they are not comparable to the later rows. The window size is nominally 3, but the effective sample size grows from 1 to 3 over the first rows.
Seeing the effective window size
When you lower min_periods, check how many observations each result used. Use count() on the same rolling object.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
r = s.rolling(window=3, min_periods=1)
out = pd.DataFrame({"mean": r.mean(), "n": r.count()})
print(out)
# mean n
# 0 1.0 1.0
# 1 1.5 2.0
# 2 2.0 3.0
# 3 3.0 3.0
# 4 4.0 3.0
# 5 5.0 3.0count() returns floats, so n prints as 1.0, 2.0, and so on. A column like n lets you filter out weakly supported rows later, for example with out[out["n"] >= 3].
NaN values inside the data
The window counts only valid observations. A NaN in your data therefore reduces the count, even in the middle of the series. This is the most common source of unexpected gaps.
import numpy as np
import pandas as pd
s = pd.Series([1, np.nan, 3, 4, 5, 6])
print(s.rolling(window=3).mean())
# 0 NaN
# 1 NaN
# 2 NaN
# 3 NaN
# 4 4.0
# 5 5.0
print(s.rolling(window=3, min_periods=2).mean())
# 0 NaN
# 1 NaN
# 2 2.0
# 3 3.5
# 4 4.0
# 5 5.0With the default min_periods=3, a single missing value blocks every window that contains it. Rows 2 and 3 are NaN because their windows hold only two valid values. With min_periods=2, those windows produce results again. The NaN is skipped, not treated as zero, so row 2 is the mean of 1 and 3.
A related point: min_periods controls only the count check. It does not fill or interpolate missing data. If you need filled values, call fillna or interpolate before the rolling step.
Statistics that need more than one value
Some statistics are undefined for a single observation. The sample standard deviation, which pandas computes with ddof=1 by default, divides by n - 1. With one value that is a division by zero, so the result is NaN even if min_periods=1.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(window=3, min_periods=1).std())
# 0 NaN
# 1 0.707107
# 2 1.000000
# 3 1.000000
# 4 1.000000
# 5 1.000000Row 0 is NaN because std needs at least two values, not because of the window check. The same rule applies to var, cov, and corr. When you pick min_periods for these statistics, use at least 2. A larger value is usually better, since a standard deviation from two points is very noisy.
Limits on min_periods
Two limits apply.
min_periodscannot be larger thanwindowfor a fixed-size window. A window of 3 rows can never hold 4 values, so pandas raises aValueError.min_periodsmust be zero or greater. Zero is allowed, but it means a window with no valid values can still produce a result for some statistics, so you rarely want it.
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 e:
print("ValueError:", e)The check happens as soon as you build the rolling object, so the error appears even before you call mean().
min_periods with center
With center=True, the window extends both before and after each row. Missing results then appear at both ends of the data. The default check is the same: a full window is required. min_periods relaxes it at both ends at once.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(window=3, center=True).mean())
# 0 NaN
# 1 2.0
# 2 3.0
# 3 4.0
# 4 5.0
# 5 NaN
print(s.rolling(window=3, center=True, min_periods=1).mean())
# 0 1.5
# 1 2.0
# 2 3.0
# 3 4.0
# 4 5.0
# 5 5.5Row 0 averages 1 and 2 because the row before it does not exist. Row 5 averages 5 and 6 for the same reason. Window alignment gets its own chapter, so treat this as a preview.
min_periods with time-based windows
For a window given as a time span, the default is min_periods=1. That default is different from the fixed-size one, because the number of rows in a time window varies. A requirement of "3 rows" would make no sense for a window that may hold 1 row in a sparse period and 10 rows in a dense one.
You can still set min_periods to demand a minimum number of observations inside the time span.
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
df = pd.DataFrame({"sales": [10, 20, 30, 40]}, index=idx)
df["default"] = df["sales"].rolling("3D").sum()
df["min2"] = df["sales"].rolling("3D", min_periods=2).sum()
print(df)
# sales default min2
# 2024-01-01 10 10.0 NaN
# 2024-01-02 20 30.0 30.0
# 2024-01-04 30 50.0 50.0
# 2024-01-07 40 40.0 NaNThe row for 2024-01-07 is NaN with min_periods=2. Its window, (2024-01-04, 2024-01-07], holds only one observation. This shows how min_periods works as a data-quality guard on irregular data: a NaN marks a stretch with too few observations, and you can tell it apart from a stretch with enough of them.
min_periods with expanding
An expanding window always starts at the first row, so it is also affected by min_periods. The default is 1, so a result appears immediately. Raise it to hide the unstable early values.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.expanding(min_periods=3).mean())
# 0 NaN
# 1 NaN
# 2 2.0
# 3 2.5
# 4 3.0
# 5 3.5An expanding window never reaches a fixed size, so min_periods is the only edge control it has. The next chapters build on this.
Choosing a value
Use these rules as a starting point.
- Keep the default for fixed-size windows when comparable rows matter more than coverage. Every result then uses the same number of observations.
- Use
min_periods=1when you need a value in every row, such as for plotting a smoothed line, and the early values are not used for decisions. - Use an intermediate value, such as half the window, when you accept some warm-up but want a floor on quality.
- For
std,var,corr, andcov, use at least 2, and prefer a higher number. - Add a
count()column when downstream code needs to know how well supported each result is. - If your data has gaps, decide whether to relax
min_periodsor to fill the gaps first. The first approach computes over fewer values. The second invents values.
Common errors
- Expecting
min_periods=1to change the window size. The window still spanswindowrows. Only the requirement to compute a result changes. - Forgetting that
NaNvalues in the data count againstmin_periods, then wondering why a gap in the data grows into a longer gap in the output. - Setting
min_periodsabovewindow, which raises aValueError. - Using
min_periods=1withstdand wondering why row 0 is stillNaN. - Assuming a time-based window has the same default as a fixed-size one. It defaults to 1.
Exercise
Given s = pd.Series([2, 4, np.nan, 8, 10]), what does s.rolling(window=3, min_periods=2).mean() return for each row? Explain row 2 and row 3.
Show answer
The result is NaN, 3.0, 3.0, 6.0, 9.0. Row 0 has one valid value, so it is NaN. Row 1 averages 2 and 4, which gives 3.0. Row 2 has the window [2, 4, NaN]. Two values are valid, which meets min_periods=2, and the NaN is skipped, so the mean is 3.0. Row 3 has the window [4, NaN, 8]. Two values are valid, and their mean is 6.0. Row 4 has the window [NaN, 8, 10], whose mean is 9.0.
Exercise
You compute s.rolling(window=4, min_periods=1).std() on a Series of 10 numbers with no missing values. How many leading NaN values do you expect, and why? What would you change to avoid unreliable early values?
Show answer
Exactly one leading NaN. Row 0 has a single observation, and the sample standard deviation with ddof=1 is undefined for one value, even though minperiods=1 is satisfied. Rows 1 to 3 are computed from 2, 3, and 4 values, so they are noisy. To avoid that, raise minperiods, for example to 4 (the default), and accept the three leading NaN values. Or keep a lower value and add a count() column so you can filter out rows with too few observations.