Sub topic 12
Performance considerations
This chapter assumes you can use rolling, expanding, groupby, and apply as covered in the earlier chapters. It explains why some window calculations are fast and others are slow, and what to do about it.
Why built-in aggregations are fast
Methods such as mean, sum, std, min, and max run in compiled code. They also avoid repeated work. A rolling sum does not re-add every value in each window. It adds the value entering the window and subtracts the value leaving it. The cost grows with the number of rows, not with rows multiplied by window size.
Some aggregations cost more per window. median and quantile must keep the window's values in order, so they are slower than mean or sum.
A custom function passed to apply has no such shortcut. pandas calls your Python function once per window, and it receives every value in that window each time.
Measuring the difference
This script compares a built-in calculation with an equivalent apply. Both compute the range (max minus min) of each 100-row window.
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
s = pd.Series(rng.normal(size=200_000))
def timed(label, func):
start = time.perf_counter()
result = func()
print(f"{label}: {time.perf_counter() - start:.3f} s")
return result
roll = s.rolling(100)
builtin = timed("built-in", lambda: roll.max() - roll.min())
custom = timed(
"apply, raw=True",
lambda: roll.apply(lambda w: w.max() - w.min(), raw=True),
)
print(np.allclose(builtin, custom, equal_nan=True))The two results match, so the check prints True. Timings depend on your machine, but the built-in version is usually much faster. Always check that both versions give the same answer before you swap one for the other.
Choosing an approach
Combine built-ins when you can. In the example above, max() - min() replaced a custom function. A rolling range, a rolling coefficient of variation (std() / mean()), and a rolling z-score can all be built from built-ins.
Making apply cheaper
If you must use apply, start with raw=True. It passes each window as a NumPy array instead of building a new Series for every window. Your function must then work on arrays, not use index labels.
For heavy custom functions, pandas can compile your function with Numba.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
s = pd.Series(rng.normal(size=200_000))
def value_range(window):
return window.max() - window.min()
result = s.rolling(100).apply(value_range, raw=True, engine="numba")
print(result.tail())This needs the numba package installed and raw=True. The first call includes compile time, so the gain shows on large inputs or repeated calls. To reuse the compiled function, pass engine_kwargs={"cache": True}. The function body must use only features Numba supports. If compilation fails, fall back to the default engine.
Reducing the work itself
- Use the
stepargument. If you only need a result every N rows,s.rolling(100, step=10).mean()computes one window in ten. It requires pandas 1.5 or later. The result is shorter and has the index labels of the rows it kept. - Select columns first. Call
df[["price"]].rolling(20).mean()instead of rolling the whole DataFrame and discarding columns later. - Use numeric dtypes. Windows over
float64columns are fast. Windows overobjectcolumns are not meaningful and may raise errors. - Watch grouped windows.
groupby(...).rolling(...)builds windows for each group. With many small groups, the overhead per group adds up. Check timing on realistic data. - Remember time-based windows. A
"7D"window needs the index to be monotonic and computes window edges from timestamps. It is usually fine, but it is not free compared with a fixed row count. - Consider
ewm. Exponentially weighted means use a recurrence and run in compiled code. They are a good choice when a soft window suits your problem.
Exercise
You compute a rolling 50-row median of a very large Series with s.rolling(50).apply(np.median, raw=True) and it is slow. What would you try first, and what would you check afterward?
Show answer
Replace it with the built-in s.rolling(50).median(), which runs in compiled code and avoids a Python call per window. Then compare the two results with np.allclose(..., equal_nan=True) to confirm they match, and time both. If you only need a value every few rows, adding step reduces the work further.