Sub topic 4
Choosing aggregations: mean, sum, std, and several at once
A rolling window defines which rows are visible at each position. The aggregation decides what to compute from those rows. This chapter covers the built-in aggregations, how they treat missing values and small windows, and how to compute several at once.
It assumes you can create a Series and DataFrame, know what mean, sum and standard deviation measure, and have read the earlier chapters on rolling(window) and min_periods.
The aggregation is the last step
Every rolling expression has two parts. s.rolling(3) builds a Rolling object that only describes the windows. Nothing is computed until you call an aggregation on it.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
r = s.rolling(window=3) # describes windows, computes nothing
print(r.mean()) # computes the mean of each windowEach aggregation returns an object with the same index as the input. Position i holds the result for the window that ends at (or is centered on) position i. That is why the outputs line up with the original rows and can be assigned straight back as a new column.
The built-in aggregations
The most common methods on a Rolling object:
| Method | What each window returns | Notes |
|---|---|---|
| `mean()` | Average of the values | Smooths noise. Sensitive to outliers. |
| `sum()` | Total of the values | Totals over the last N rows or days. |
| `std()`, `var()` | Sample standard deviation, variance | `ddof=1` by default, so a window of one value gives NaN. |
| `min()`, `max()` | Smallest, largest value | Rolling highs and lows. |
| `median()` | Middle value | Resists outliers. |
| `quantile(q)` | Value at quantile `q` | `quantile(0.5)` equals `median()`. |
| `count()` | Number of non-NaN values | Does not follow the usual `min_periods` rule (see below). |
| `corr(other)`, `cov(other)` | Correlation, covariance with another series | Needs a second input. |
All of these are implemented in compiled code and update the window incrementally as it slides. Prefer them to a hand-written function whenever one exists.
Standard deviation and the ddof choice
std() and var() default to ddof=1, the sample estimate. For a window of three values, the divisor is 2, not 3. Pass ddof=0 for the population version.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(3).std())
# 0 NaN
# 1 NaN
# 2 1.0
# 3 1.0
# 4 1.0
# 5 1.0
print(s.rolling(3).std(ddof=0))
# Each full window gives about 0.816497Two consequences follow:
- With
ddof=1, a window with fewer than two valid values always gives NaN, even if you setmin_periods=1. - Rolling variance and standard deviation are computed by adding and removing values as the window moves. On data with a very large offset, such as values near 1e9 that differ by small amounts, floating-point rounding can leave small errors. Subtract a baseline first if you see this.
Missing values inside windows
Aggregations skip NaN, but a window only produces a result if it holds at least min_periods valid values. The default min_periods equals the window size. So one NaN inside a window of three makes that result NaN under the default.
import numpy as np
import pandas as pd
s = pd.Series([1, 2, np.nan, 4, 5, 6])
print(s.rolling(3).sum())
# 0 NaN
# 1 NaN
# 2 NaN
# 3 NaN
# 4 NaN
# 5 15.0
print(s.rolling(3, min_periods=2).sum())
# 0 NaN
# 1 3.0
# 2 3.0
# 3 6.0
# 4 9.0
# 5 15.0With min_periods=2, the window [1, 2, NaN] sums its two valid values. This is a choice you make on purpose. A sum over two valid values is a smaller total than a sum over three, so the results are not comparable. For mean, median and std the lower count matters less.
count() is the exception. It reports how many valid values each window holds, including partial windows at the start.
import numpy as np
import pandas as pd
s = pd.Series([2, 3, np.nan, 10])
print(s.rolling(2).count())
# 0 1.0
# 1 2.0
# 2 1.0
# 3 1.0A common pattern is to compute count() next to sum() so you can see how many values supported each total.
Mean or median
The mean uses every value, so one extreme value pulls the result up for as long as it stays in the window. The median ignores how large the extreme value is.
import pandas as pd
s = pd.Series([1, 2, 100, 4, 5, 6])
out = s.rolling(3).agg(["mean", "median"]).round(1)
print(out)
# mean median
# 0 NaN NaN
# 1 NaN NaN
# 2 34.3 2.0
# 3 35.3 4.0
# 4 36.3 5.0
# 5 5.0 5.0The value 100 inflates the mean for three consecutive windows. The median stays near the typical values. Use the median when spikes are errors or one-off events. Use the mean when spikes are real and should count. The median costs more to compute than the mean, which matters on very large inputs.
Several aggregations at once
Pass a list of names to agg to compute several statistics over the same windows. On a Series, you get 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.0Use string names such as "mean" where you can. They map to the fast built-in methods. A lambda in the list also works, but it runs through the slower custom path and gets the column name <lambda>. A later chapter covers custom functions.
DataFrames and column control
On a DataFrame, a list applies every aggregation to every column and the result has two-level column labels. A dict lets you choose aggregations per column.
import pandas as pd
df = pd.DataFrame({
"sales": [10, 20, 30, 40],
"visits": [1, 2, 3, 4],
})
out = df.rolling(2).agg({
"sales": ["mean", "max"],
"visits": "sum",
})
print(out.columns.tolist())
# [('sales', 'mean'), ('sales', 'max'), ('visits', 'sum')]
out.columns = ["_".join(c) for c in out.columns]
print(out)
# sales_mean sales_max visits_sum
# 0 NaN NaN NaN
# 1 15.0 20.0 3.0
# 2 25.0 30.0 5.0
# 3 35.0 40.0 7.0Flattening the labels into names like sales_mean makes the result easy to join back onto the original frame with df.join(out).
Two-input aggregations
corr and cov compare two series over the same window. Call them on the Rolling object and pass the other series.
import pandas as pd
a = pd.Series([1, 2, 3, 4, 5, 6])
b = pd.Series([2, 4, 5, 4, 3, 1])
print(a.rolling(3).corr(b))The two inputs are aligned on their index first. If the indexes differ, rows that exist in only one input produce NaN. Within any window where one input is constant, the correlation is undefined and the result is NaN.
Choosing an aggregation
The question to ask is what you want to know about the recent past.
Some practical pairings:
- Rolling mean and rolling std together give a band around the trend. Values far outside
mean ± 2 * stdare candidates for anomalies. - Rolling max and min give a channel, such as a 20-day high and low.
- Rolling sum over a fixed number of rows gives period totals, such as units sold in the last 7 rows.
- Rolling count tells you how much data stands behind each of the other numbers.
Common errors
- Reading the first rows as zero. Leading NaN means "not enough data", not zero. Filling with 0 distorts later statistics.
- Std of a single value.
rolling(1).std()is all NaN underddof=1. Use a window of at least 2 or setddof=0. - Mixing partial and full windows. With a low
min_periods, early rows use fewer values than later rows. Asumthere looks like growth that is not real. - Passing a function result instead of a name.
agg([np.mean])can work but may emit warnings in recent pandas versions. Use"mean". - Assuming the window includes future rows. By default the window ends at the current row. Alignment is covered in the next chapter.
Exercise
Given s = pd.Series([4, 8, 6, 10, 12]), write one expression that returns a DataFrame with the rolling mean and rolling max over a window of 2 rows. What are the values in the mean and max columns?
Show answer
s.rolling(2).agg(["mean", "max"]). The mean column is NaN, 6.0, 7.0, 8.0, 11.0 and the max column is NaN, 8.0, 8.0, 10.0, 12.0. The first row is NaN because the default min_periods equals the window size, and only one value is available there.
Exercise
s = pd.Series([5, np.nan, 7, 8, 9]). Why does s.rolling(3).sum() return NaN for every row, and what single change makes it return a number for the third row onward?
Show answer
Each window of three rows from position 2 onward still contains the NaN at position 1 or has fewer than three valid values, and the default minperiods is 3, so every result is NaN. Setting `minperiods=2 allows a result when at least two valid values are present: s.rolling(3, min_periods=2).sum()`. This gives 12.0 at position 2, 15.0 at position 3 and 24.0 at position 4.