Sub topic 7
Expanding Windows for Running Statistics
This chapter assumes you can build a Series or DataFrame, you know rolling(window).mean() from the earlier chapters, and you are comfortable with groupby. It covers how an expanding window works, how it differs from the cumulative methods, and the mistakes people make with it.
What an expanding window is
A rolling window slides along the data and keeps a fixed size. An expanding window is anchored at the first row and grows by one row at each step. The result at row t is the statistic computed over rows 0 through t, inclusive.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.expanding().mean())
# 0 1.0
# 1 1.5
# 2 2.0
# 3 2.5
# 4 3.0
# 5 3.5
print(s.expanding().max())The mean at row 3 is (1 + 2 + 3 + 4) / 4 = 2.5. Each result uses every row seen so far, so expanding windows suit running totals, running averages, running extremes and "all history so far" features.
The window grows only forward. There is no window size to choose, so expanding() takes no window argument.
How it differs from rolling
An expanding window behaves like a rolling window whose size is the whole series, with min_periods=1. For a series s, s.expanding().mean() and s.rolling(window=len(s), min_periods=1).mean() give the same values. The expanding form is clearer and doesn't depend on the length.
| Feature | `rolling(3)` | `expanding()` |
|---|---|---|
| Window start | Moves with the current row | Fixed at the first row |
| Window size | Constant (3 rows) | Grows by one row per step |
| Default `min_periods` | Equal to the window size | 1 |
| Time offsets such as `"7D"` | Supported | Not supported |
| Typical use | Smoothing, recent trend | Running totals, all-history features |
The second row of the table explains a common surprise. rolling(3) returns NaN for the first two rows, but expanding() returns a value from the first row onward.
Controlling the start with min_periods
The default is min_periods=1. You can raise it when a statistic is not meaningful on a few observations.
import pandas as pd
s = pd.Series([2, 4, 4, 4, 5, 5, 7, 9])
print(s.expanding(min_periods=3).mean())
# 0 NaN
# 1 NaN
# 2 3.333333
# 3 3.5
# 4 3.8
# 5 4.0
# 6 4.428571
# 7 5.0Some statistics need more than one observation regardless of min_periods. The standard deviation uses ddof=1, so the first value is always NaN:
import pandas as pd
s = pd.Series([2, 4, 4, 4, 5, 5, 7, 9])
print(s.expanding().std().head(3))
# 0 NaN
# 1 1.414214
# 2 1.154701min_periods counts valid (non-NaN) observations, not rows. This matters when the data has gaps:
import numpy as np
import pandas as pd
s = pd.Series([1, np.nan, 3, 4])
print(s.expanding().mean())
# 0 1.000000
# 1 1.000000
# 2 2.000000
# 3 2.666667
print(s.expanding(min_periods=3).mean())
# 0 NaN
# 1 NaN
# 2 NaN
# 3 2.666667At row 2 the window holds three rows but only two valid values, so the second call still returns NaN there.
Choosing aggregations
Expanding windows support the same built-in statistics as rolling windows: count, sum, mean, median, min, max, std, var, skew, kurt, quantile, sem, corr and cov. To compute several at once, pass a list to agg:
import pandas as pd
s = pd.Series([3, 1, 4, 1, 5, 9])
print(s.expanding().agg(["mean", "min", "max"]))The result is a DataFrame with one column per aggregation. On a DataFrame, df.expanding().mean() works column by column.
Expanding versus the cumulative methods
pandas also has cumsum, cumprod, cummax and cummin. For sums and extremes they give the same numbers as expanding(), and they are faster. They differ in how they treat missing values:
import numpy as np
import pandas as pd
s = pd.Series([1, np.nan, 3])
print(s.cumsum())
# 0 1.0
# 1 NaN
# 2 4.0
print(s.expanding().sum())
# 0 1.0
# 1 1.0
# 2 4.0cumsum keeps NaN at the position of the missing input. expanding().sum() returns the running total at every row, because the window at row 1 still contains one valid value. Choose based on whether a missing input should show up as a gap in the output.
Use the cum* methods when one exists for your statistic and you need speed. Use expanding() for everything else, such as mean, std, median and quantile, which have no cum* equivalent.
A worked example: drawdown
A drawdown measures how far a price has fallen from its highest earlier value. The running peak is an expanding maximum.
import pandas as pd
df = pd.DataFrame({"price": [100, 110, 105, 120, 90, 95]})
df["peak"] = df["price"].expanding().max()
df["drawdown"] = (df["price"] / df["peak"] - 1).round(3)
print(df)
# price peak drawdown
# 0 100 100.0 0.000
# 1 110 110.0 0.000
# 2 105 110.0 -0.045
# 3 120 120.0 0.000
# 4 90 120.0 -0.250
# 5 95 120.0 -0.208
print(df["drawdown"].min())
# -0.25The peak column never decreases. That property always holds for an expanding maximum, and it is a quick sanity check on your results.
Expanding windows and time
expanding() ignores timestamps. Even with a DatetimeIndex it counts rows, and it doesn't accept an offset string such as "30D". A time-limited window needs rolling("30D"), which was covered in the previous chapter.
A common time-aware running statistic is "since the start of the year". Restart the accumulation at each year by grouping on the year, then use a cum* method or an expanding window:
import pandas as pd
idx = pd.to_datetime(["2023-12-30", "2023-12-31", "2024-01-01", "2024-01-02"])
df = pd.DataFrame({"sales": [5, 5, 10, 20]}, index=idx)
df["ytd_sales"] = df.groupby(df.index.year)["sales"].cumsum()
print(df)
# sales ytd_sales
# 2023-12-30 5 5
# 2023-12-31 5 10
# 2024-01-01 10 10
# 2024-01-02 20 30The data must be sorted by time. An expanding window follows row order, not timestamp order, so unsorted data gives wrong results without any error.
Expanding windows within groups
To restart the window for each group, call expanding() after groupby. The result has a MultiIndex of group key and original index. Drop the group level to align it back onto the original rows:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 30],
})
df["run_avg"] = (
df.groupby("store")["sales"]
.expanding()
.mean()
.reset_index(level=0, drop=True)
)
print(df)
# store sales run_avg
# 0 A 1 1.0
# 1 A 2 1.5
# 2 A 3 2.0
# 3 B 10 10.0
# 4 B 20 15.0
# 5 B 30 20.0Store B starts again at 10.0 instead of continuing from store A's history. If your rows are not already ordered so that each group's rows appear in chronological order, sort first. The reset_index trick relies on the original index being unique.
Avoiding look-ahead leakage
An expanding statistic at row t includes row t. If you use it as a feature to predict the value at row t, the feature contains the answer. Shift the result down by one row so each feature uses only earlier rows:
import pandas as pd
df = pd.DataFrame({"sales": [10, 20, 30, 40]})
df["hist_mean"] = df["sales"].expanding().mean().shift(1)
print(df)
# sales hist_mean
# 0 10 NaN
# 1 20 10.0
# 2 30 15.0
# 3 40 20.0Per group, put the shift inside the group so that the first row of each group becomes NaN, and history never leaks from one group into the next:
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 30],
})
df["hist_mean"] = df.groupby("store")["sales"].transform(
lambda s: s.expanding().mean().shift(1)
)
print(df["hist_mean"].tolist())
# [nan, 1.0, 1.5, nan, 10.0, 15.0]Custom functions with apply
When no built-in statistic fits, use expanding().apply(func, raw=True). With raw=True each window arrives as a NumPy array, which is faster than a Series.
import pandas as pd
s = pd.Series([3, 1, 4, 1, 5])
print(s.expanding().apply(lambda w: w.max() - w.min(), raw=True))
# 0 0.0
# 1 2.0
# 2 3.0
# 3 3.0
# 4 4.0The cost grows quickly. Window t has t + 1 values, so the total work for n rows is on the order of n². A rolling window of fixed size costs roughly n times the window size. On a million rows, a custom expanding function is very slow, so first look for a built-in or cum* equivalent.
Common errors
- Expecting leading NaN.
expanding()starts at row 0 becausemin_periodsdefaults to 1. Setmin_periodsexplicitly if the first few values are unreliable. - Passing a window size.
expanding(3)does not mean "window of 3". The first positional argument ismin_periods, so this sets a minimum of 3 observations. - Using an offset.
expanding("7D")fails. Userolling("7D")for time spans. - Unsorted data. Sort by time (and by group) before expanding.
- Mixing up group alignment. After
groupby(...).expanding(), assign back only afterreset_index(level=0, drop=True), or the assignment aligns on a MultiIndex and fails or producesNaN. - Forgetting the shift. A feature built from
expanding()withoutshift(1)leaks the current target into the model.
Exercise
A Series is pd.Series([4, 8, 6, 10]). Write the call that gives, for each row, the mean of only the previous rows (not the current one), and state the four resulting values.
Show answer
s.expanding().mean().shift(1). The expanding means are 4.0, 6.0, 6.0, 7.0. After the shift the values are NaN, 4.0, 6.0, 6.0.
Exercise
Given s = pd.Series([2.0, None, 5.0]), what do s.cumsum() and s.expanding().sum() return, and why do they differ?
Show answer
s.cumsum() returns 2.0, NaN, 7.0. s.expanding().sum() returns 2.0, 2.0, 7.0. Both skip the missing value when summing. cumsum keeps NaN at the position of the missing input. The expanding window at row 1 still holds one valid value, and the default min_periods=1 is satisfied, so it returns the running total.
Exercise
A DataFrame has columns team and points, sorted by team and then by date. Write one line that adds a column best_so_far, the highest points value each team has reached up to and including the current row.
Show answer
df["best_so_far"] = df.groupby("team")["points"].cummax(). The equivalent expanding form is df.groupby("team")["points"].expanding().max().reset_index(level=0, drop=True). The cummax form is shorter and faster.