Sub topic 4
Choosing aggregations: mean, sum, std, and several at once
This chapter assumes you can create pandas Series and DataFrames, read basic statistics such as mean, sum and standard deviation, and call rolling(window) from the previous chapters. Here you pick the statistic each window computes and compute several at once.
Aggregation methods on a rolling window
rolling(window) returns a Rolling object. It holds the window definition and calculates nothing yet. Calling an aggregation method on it applies that statistic to every window.
| Method | What each window returns |
|---|---|
| `mean()` | Average of the values |
| `sum()` | Total of the values |
| `std()` / `var()` | Sample standard deviation / variance (`ddof=1`) |
| `min()` / `max()` | Smallest / largest value |
| `median()` | Middle value |
| `count()` | Number of non-NaN values |
| `quantile(q)` | Value at quantile `q` |
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(window=3).sum())
print(s.rolling(window=3).std())The first two results are NaN in both outputs, because a 3-row window is not full yet. After that, sum() gives 6, 9, 12, 15. std() gives 1.0 each time, because every window holds three consecutive integers.
The ddof gotcha
Rolling std() and var() use ddof=1, the sample formula. This matches Series.std() but differs from NumPy's np.std, which defaults to ddof=0. For the window [1, 2, 3], ddof=1 gives 1.0 and ddof=0 gives about 0.8165.
print(s.rolling(window=3).std(ddof=0))A window of one row has no sample standard deviation. With min_periods=1, the first std() result is therefore still NaN.
Several aggregations at once
Pass a list to agg to compute several statistics over the same windows. The result is a DataFrame with one column per aggregation.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(window=3).agg(["mean", "min", "max"]))
# mean min max
# 0 NaN NaN NaN
# 1 NaN NaN NaN
# 2 2.0 1.0 3.0
# 3 3.0 2.0 4.0
# 4 4.0 3.0 5.0
# 5 5.0 4.0 6.0One agg call is shorter than three separate calls and keeps the results aligned in one frame. You can pass method names as strings, as above, or callables such as np.median. Strings are preferred because pandas can then use its optimized implementation.
Different aggregations per column
On a DataFrame, rolling applies to every numeric column. To choose a statistic for each column, pass a dictionary.
import pandas as pd
df = pd.DataFrame({
"price": [10, 12, 11, 15, 14, 16],
"volume": [100, 120, 90, 150, 130, 160],
})
out = df.rolling(window=3).agg({"price": "mean", "volume": "sum"})
print(out)
# price volume
# 0 NaN NaN
# 1 NaN NaN
# 2 11.000000 310.0
# 3 12.666667 360.0
# 4 13.333333 370.0
# 5 15.000000 440.0If you pass a list to a DataFrame's agg, the columns become a two-level index. The first level is the original column and the second is the aggregation, as in ("price", "mean"). Select a column with out["price"] to get back to a flat frame.
Missing values inside a window
Aggregations skip NaN values inside a window. The window still needs at least min_periods valid observations, and by default that equals the window size. One missing value in a 3-row window therefore makes that result NaN. Lower min_periods if you want results from partly filled windows.
Exercise
Given df with columns "price" and "volume", write a call that returns the 4-row rolling maximum of price and the 4-row rolling mean of volume in one result. How many leading rows are NaN?
Show answer
df.rolling(window=4).agg({"price": "max", "volume": "mean"}). The first 3 rows are NaN in both columns, because min_periods defaults to the window size (4) and the first full window ends at row index 3.
Exercise
A window holds the values [2, 4, 6]. What do rolling std() and std(ddof=0) return for it?
Show answer
std() returns 2.0 (sample formula, divide by n-1 = 2). std(ddof=0) returns about 1.633 (divide by n = 3).