Sub topic 1
Rolling and Expanding Windows in pandas
Prerequisites
You should know how to create and index pandas Series and DataFrames, use a DatetimeIndex, calculate basic statistics, and group data with groupby.
What a window calculation is
A window calculation computes a value from a limited set of neighboring rows. The set of rows is the window. As pandas moves through the data, the window moves too.
This differs from a plain aggregation. s.mean() produces one value from the entire Series. A rolling calculation produces one value for each row. It also differs from groupby: grouping separates rows into categories, while a window selects nearby rows within the current position.
Fixed-size rolling windows
Use rolling(window=n) when each window should contain a fixed number of rows. The following code calculates a three-row moving mean:
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
moving_mean = s.rolling(window=3).mean()
print(moving_mean)The first result is NaN because the first row does not have three values available. The second result is also NaN. Starting at index 2, each result uses the current row and the two preceding rows:
- Index 2:
(1 + 2 + 3) / 3 = 2 - Index 3:
(2 + 3 + 4) / 3 = 3
The window is based on row count, not elapsed time. A later chapter covers time-based windows such as "7D".
Controlling the edges with `min_periods`
min_periods sets the minimum number of non-missing values required for a result. To calculate a partial mean at the beginning, set it to 1:
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.0Use the default behavior when a statistic is meaningful only with a complete window. Use a smaller min_periods when early results are useful and you can accept that they use fewer observations.
Exercise
What does s.rolling(3).mean() return at index 1 for s = [10, 20, 30], and how can you produce a value there?
Show answer
It returns NaN because only two rows are available. Use s.rolling(3, min_periods=1).mean() to return 15.0.