Sub topic 10
Custom window functions with apply
This chapter shows how to run your own function on each window when no built-in aggregation fits. It assumes you can already build a rolling window, set min_periods, and read the leading NaN values from earlier chapters.
When to use apply
Built-in methods such as mean, sum, std, min and max cover most cases. Use rolling(...).apply(func) when the statistic you need is not available, for example the range of a window or a weighted average with your own weights.
apply calls func once per window. The function receives the window's values and must return a single number. expanding().apply(func) works the same way, but the window grows from the first row.
A first custom function
This example computes the range (maximum minus minimum) of each 3-row window.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(window=3).apply(lambda w: w.max() - w.min(), raw=True))
# 0 NaN
# 1 NaN
# 2 2.0
# 3 2.0
# 4 2.0
# 5 2.0The first two results are NaN because the windows are incomplete. With the default min_periods, pandas does not call your function on them. If you set min_periods=1, your function will also receive shorter windows, so it must handle them.
raw=True and raw=False
The raw argument decides what type of object your function receives.
| `raw` | Function receives | Use when |
|---|---|---|
| `True` | A NumPy array | The function only needs values. This is faster. |
| `False` (default) | A Series with its index | The function needs labels or Series methods such as `rank`. |
A weighted average works well with raw=True, because np.dot operates on arrays:
import numpy as np
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
weights = np.array([0.2, 0.3, 0.5])
weighted = s.rolling(window=3).apply(lambda w: np.dot(w, weights), raw=True)
print(weighted.round(1))
# 0 NaN
# 1 NaN
# 2 2.3
# 3 3.3
# 4 4.3
# 5 5.3The weights are ordered oldest to newest, so the current row gets the largest weight.
When you need Series methods, use raw=False. This example finds where the newest value ranks inside its window:
import pandas as pd
s = pd.Series([3, 1, 4, 1, 5, 9])
rank_of_last = s.rolling(window=3).apply(lambda w: w.rank().iloc[-1], raw=False)
print(rank_of_last)
# 0 NaN
# 1 NaN
# 2 3.0
# 3 1.5
# 4 3.0
# 5 3.0A rank of 3.0 means the newest value is the largest in its window. The 1.5 in row 3 comes from a tie: the two 1s share ranks 1 and 2.
Common errors
- Returning more than one value. The function must return a scalar. Returning a list or a Series raises an error. To get several statistics, use
aggwith a list of built-in names instead. - Passing a non-numeric column. Window functions expect numeric data. Convert or drop other columns first.
- Forgetting that
raw=Falseis the default. Code written for arrays, such asw[0], may behave differently on a Series. Setraw=Trueexplicitly when you want an array. - Assuming the function sees every row. With the default
min_periods, incomplete windows are skipped and produceNaN.
Exercise
Exercise
You call s.rolling(4).apply(lambda w: w[-1] - w[0], raw=True) on a Series of 10 numbers. How many NaN values does the result contain, and why would the same lambda be risky with raw=False?
Show answer
The result has 3 NaN values, because the first three windows have fewer than 4 values and min_periods defaults to the window size. With raw=False, w is a Series with a DatetimeIndex or integer index, so w[-1] looks up a label instead of the last position. It can raise a KeyError or return the wrong value. Use w.iloc[-1] - w.iloc[0] instead.