Sub topic 10
Custom window functions with apply
Built-in window methods such as mean(), sum() and std() cover most needs. Sometimes the statistic you want has no built-in method, such as a mean absolute deviation, a percentile rank of the latest value, or a domain-specific score. For those cases pandas offers rolling().apply(), which runs your own function on every window.
This chapter assumes you know fixed-size rolling windows, min_periods, and the leading NaN values they produce. It also assumes you are comfortable with NumPy arrays and lambda functions.
How apply works
apply calls your function once for each window and collects the returned numbers into a new Series. Your function receives the window's values and must return one number.
Here is the example from the plan. It computes the range (max minus min) 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 for the same reason as with built-in aggregations. The window is not full yet, and min_periods defaults to the window size. Your function is never called for those rows.
The output is always float64, even when your function returns integers. pandas converts each result to a float.
raw=True versus raw=False
The raw argument controls what your function receives. It is required in practice, because the default is raw=False, which is the slower mode.
| Setting | Function receives | Speed | Use it when |
|---|---|---|---|
| `raw=True` | A NumPy `ndarray` | Faster | You only need the values |
| `raw=False` (default) | A `Series` with the original index labels | Slower | You need labels, `idxmax()`, or Series methods |
With raw=True, you can use NumPy functions and positional indexing such as w[-1]. With raw=False, w[-1] on an integer-indexed Series would look up a label, so use w.iloc[-1] instead.
This example needs the index labels, so it uses raw=False. It counts how many rows ago the window's maximum occurred.
import pandas as pd
s = pd.Series([3, 1, 4, 1, 5, 9, 2, 6])
rows_since_max = s.rolling(3).apply(
lambda w: w.index[-1] - w.idxmax(), raw=False
)
print(rows_since_max)
# 0 NaN
# 1 NaN
# 2 0.0
# 3 1.0
# 4 0.0
# 5 0.0
# 6 1.0
# 7 2.0The window Series keeps the labels of the original rows. That is why w.idxmax() returns a label from the original index.
Writing a function that returns a scalar
The function must return a single number. Returning an array, a list, or a Series raises a TypeError, because pandas needs one value per window.
Common correct patterns:
import numpy as np
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
# Mean absolute deviation around the window mean
mad = s.rolling(3).apply(lambda w: np.abs(w - w.mean()).mean(), raw=True)
print(mad)
# 0 NaN
# 1 NaN
# 2 0.666667
# 3 0.666667
# 4 0.666667
# 5 0.666667A second pattern ranks the newest value within its window, which has no built-in method.
import pandas as pd
s = pd.Series([3, 1, 4, 1, 5, 9, 2, 6])
beaten = s.rolling(3).apply(lambda w: (w[:-1] < w[-1]).sum(), raw=True)
print(beaten)
# 0 NaN
# 1 NaN
# 2 2.0
# 3 0.0
# 4 2.0
# 5 2.0
# 6 0.0
# 7 1.0Each result is the number of earlier values in the window that are smaller than the newest one. At row 2 the window is [3, 1, 4], and 4 beats both 3 and 1, so the result is 2.
Passing extra arguments
A lambda that closes over a variable works, but a named function with parameters is easier to test and reuse. apply forwards args and kwargs to your function after the window.
import pandas as pd
def share_above(w, threshold):
return (w > threshold).mean()
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(3).apply(share_above, raw=True, args=(3,)))
# 0 NaN
# 1 NaN
# 2 0.000000
# 3 0.333333
# 4 0.666667
# 5 1.000000You can also pass kwargs={"threshold": 3} instead of args=(3,). The first positional parameter of your function is always the window.
A weighted rolling mean follows the same pattern. The weights array has the same length as the window, and np.dot multiplies each value by its weight.
import numpy as np
import pandas as pd
weights = np.array([0.2, 0.3, 0.5])
def weighted_mean(w, weights):
return np.dot(w, weights)
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.rolling(3).apply(weighted_mean, raw=True, args=(weights,)).round(1))
# 0 NaN
# 1 NaN
# 2 2.3
# 3 3.3
# 4 4.3
# 5 5.3This function assumes every window has exactly three values. That holds here because min_periods defaults to the window size. If you lower min_periods, edge windows are shorter and np.dot raises a shape error. The next section covers that.
Edge windows and missing values
Two behaviors affect custom functions more than built-in aggregations.
- Short windows. If you set
min_periodsbelow the window size, your function is called on shorter arrays at the start of the data. A function that assumes a fixed length, such as the weighted mean above, breaks. Write the function to uselen(w), or keep the defaultmin_periods. - NaN inside the window. pandas counts only non-missing values toward
min_periods, but the window passed to your function still contains theNaNvalues. NumPy functions such asmean()then returnNaN. Usenp.nanmean,np.nanmaxand similar functions when your data has gaps.
import numpy as np
import pandas as pd
s = pd.Series([1.0, np.nan, 3.0, 4.0, 5.0])
result = s.rolling(3, min_periods=2).apply(np.nanmean, raw=True)
print(result)
# 0 NaN
# 1 NaN
# 2 2.0
# 3 3.5
# 4 4.0Row 1 has only one non-missing value in its window of two rows, which is below min_periods=2, so the function is not called. Row 2 has a window [1, NaN, 3] with two valid values, so np.nanmean returns 2.0.
Windows that are not fixed-size
apply works with every window type covered earlier. With a time-based window such as rolling("3D"), the function receives however many rows fall in each time span, so lengths vary from row to row. Write such functions without assuming a length.
With expanding().apply(func, raw=True), the window grows from the first row, so the function receives longer and longer arrays. Each call does more work than the one before.
After groupby, rolling(...).apply(...) runs within each group, and the result has a group level in its index. As with built-in aggregations, remove that level with reset_index(level=0, drop=True) to align the result with the original rows.
A custom function sees one column at a time. If your statistic needs two columns at once, such as a rolling regression slope, apply cannot do it directly. Use the built-in rolling().corr() or rolling().cov() where they fit.
Performance
apply is the slowest way to compute a window statistic. Built-in methods run in compiled code and update their result incrementally as the window slides. apply calls a Python function for every window and passes it the full window each time, so the work grows with n × window.
When a built-in or a combination of built-ins gives the same answer, prefer it. The range example from the start can be written without apply:
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
roll = s.rolling(3)
print(roll.max() - roll.min())
# 0 NaN
# 1 NaN
# 2 2.0
# 3 2.0
# 4 2.0
# 5 2.0This gives the same values as the apply version and runs much faster on large data. Work through these options in order:
- Express the statistic with built-in rolling methods and arithmetic, as above.
- Use
raw=Trueso each window arrives as a NumPy array. - For heavy functions on large data, use the Numba engine. It compiles your function and requires
raw=Trueand thenumbapackage.
import numpy as np
import pandas as pd
def mean_abs_dev(x):
return np.fabs(x - x.mean()).mean()
s = pd.Series(np.arange(1_000_000, dtype="float64"))
result = s.rolling(100).apply(mean_abs_dev, engine="numba", raw=True)
print(result.iloc[99])The first call includes compilation time, so Numba pays off only for large inputs or repeated calls. The function must use only operations Numba supports, and it fails with a typing error otherwise.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError` about converting to float | The function returned an array, list, or Series | Return one number, for example with `.sum()` or `.mean()` |
| `KeyError` on `w[-1]` | `raw=False` with a Series, where `[-1]` looks up a label | Use `w.iloc[-1]`, or switch to `raw=True` |
| Shape mismatch error at the start | Shorter windows from a low `min_periods` | Use `len(w)` in the function, or keep the default `min_periods` |
| All results `NaN` after adding gaps | The function does not skip `NaN` | Use `np.nanmean` and similar |
| Very slow run | Python-level function on a large Series | Use built-ins, `raw=True`, or `engine="numba"` |
Exercise
A colleague writes s.rolling(3).apply(lambda w: [w.min(), w.max()], raw=True) to get both values for each window. It raises an error. Why, and how would you get a result with both statistics?
Show answer
apply requires the function to return one scalar per window, and a list is not a scalar. Use s.rolling(3).agg(["min", "max"]) to get a DataFrame with one column per statistic. Alternatively, call apply twice, once for each statistic. The built-in agg version is also faster.
Exercise
Given s = pd.Series([2, 8, 5, 9, 4]), write a call that returns, for each full 3-row window, the fraction of values strictly greater than the window mean. Which raw value do you choose, and why? What is the result at row 2?
Show answer
Use s.rolling(3).apply(lambda w: (w > w.mean()).mean(), raw=True). Choose raw=True because the function only needs the values and NumPy operations, which is faster than receiving a Series. At row 2 the window is [2, 8, 5] with mean 5.0. Only 8 is greater than 5.0, so the result is 1/3, about 0.333333. Rows 0 and 1 are NaN.