Sub topic 12
Performance considerations
This chapter assumes you know the rolling, expanding and ewm methods from the earlier chapters, can use a DatetimeIndex, and have run groupby in pandas. Here you learn which window operations are cheap, which are expensive, and how to measure the difference.
Where the time goes
Calling s.rolling(50) does almost no work. It returns a Rolling object that records the window settings. The computation happens when you call an aggregation such as .mean() or .apply(...). This has two consequences:
- Creating the window object is free, and you can reuse it for several aggregations.
- The cost is set by the aggregation you pick, not by the window object.
The built-in aggregations run in compiled code (Cython). Most of them avoid recomputing each window from scratch. When the window moves forward one row, they add the new value and remove the oldest one. The work per row is then roughly constant, however large the window is.
| Aggregation | How it is computed | Cost as the window grows |
|---|---|---|
| `sum`, `mean`, `count` | Add the new value, remove the old one | Roughly constant per row |
| `var`, `std`, `skew`, `kurt` | Same idea, updating running moments | Roughly constant per row |
| `min`, `max` | Compiled code that tracks the current extreme | Roughly constant per row |
| `median`, `quantile` | Compiled code that keeps the window sorted | Grows slowly with window size |
| `apply(func)` | Calls your function once per window | Grows with window size, plus a Python call per row |
The last row is the one to watch. A rolling apply on a million rows makes a million function calls, and each call looks at every value in its window.
Prefer built-in aggregations
If a built-in method can express your calculation, use it. The range of each window (maximum minus minimum) is a good test. You can write it with apply, or you can combine two built-in aggregations:
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
s = pd.Series(rng.normal(size=50_000))
def timed(label, func):
start = time.perf_counter()
result = func()
elapsed = time.perf_counter() - start
print(f"{label:<28}{elapsed:8.3f} s")
return result
r = s.rolling(50)
fast = timed("rolling max minus min", lambda: r.max() - r.min())
raw = timed("apply, raw=True", lambda: r.apply(lambda w: w.max() - w.min(), raw=True))
slow = timed("apply, raw=False", lambda: r.apply(lambda w: w.max() - w.min()))
print(np.allclose(fast, raw, equal_nan=True))
print(np.allclose(fast, slow, equal_nan=True))The three results are the same, and both comparisons print True. The timings depend on your machine, but the order is stable. The two built-in calls are fastest. apply with raw=True is much slower. apply with the default raw=False is slowest.
The reason for the last gap is what each window looks like when it reaches your function:
- With
raw=False, pandas builds a newSeriesfor every window, with an index and metadata. Your function receives that object. - With
raw=True, pandas passes a plain NumPy array. There is no per-windowSeriesto build, so each call is cheaper.
Use raw=True whenever your function only needs the values. Keep raw=False only when the function needs the index labels of the window.
Reuse the window object and count the passes
Each aggregation is a separate pass over the data. Reusing the window object saves you from retyping the settings, but it does not make two aggregations cost one:
r = s.rolling(50)
mean = r.mean()
std = r.std()The same applies to a list passed to agg, as in r.agg(["mean", "min", "max"]). It is convenient, but pandas still computes each aggregation on its own and joins the results. The total time is roughly the sum of the individual times. That is fine for built-ins. It matters if the list contains a slow function.
Also avoid computing windows you throw away. If you only need the last value of each window at every 10th row, a full rolling pass still computes every row. Rolling a downsampled series, or choosing a narrower slice before rolling, is cheaper than rolling everything and subsetting afterward.
Time-based windows need a sorted index
A window such as rolling("7D") uses the index to decide which rows belong to each window. To do this quickly, pandas requires the index to be monotonic, meaning it never goes backward. An unsorted index raises an error:
import pandas as pd
idx = pd.to_datetime(["2024-01-03", "2024-01-01", "2024-01-02"])
s = pd.Series([1, 2, 3], index=idx)
try:
s.rolling("2D").sum()
except ValueError as err:
print("ValueError:", err)
print(s.sort_index().rolling("2D").sum())The error message says the index must be monotonic. The fix is sort_index(). Sort once, near the start of your pipeline, rather than before every rolling call. Sorting a large unsorted index costs more than the rolling pass that follows it, so doing it repeatedly adds up.
Time-based windows with built-in aggregations stay fast. Each window has a different number of rows, but the add-and-remove approach still applies. Only custom functions slow down, because they receive larger arrays when the data is dense.
Rolling within groups
df.groupby("key")["value"].rolling(n).mean() handles each group separately. For a few large groups this is efficient, because each group is one compiled pass. For many small groups, such as hundreds of thousands of customer IDs with a few rows each, the per-group overhead dominates. Two things help:
- Sort by the group key first and keep the data in one DataFrame. This avoids repeated alignment work later.
- Check whether you need a window at all. For a running (expanding) sum per group,
groupby(...).cumsum()is a single compiled operation and avoids the window machinery.
If you must use rolling per group, the result carries the group key as an extra index level. Dropping it with reset_index(level=0, drop=True), as shown in the earlier chapter, is cheap. Be aware that the output follows group order, which can differ from the original row order if the groups were interleaved. Aligning back by index is correct, but it costs a reindex, so do it once at the end.
Expanding windows and cost
expanding().mean() and the other built-ins are as cheap as their rolling versions. The cost of expanding().apply(func) is different. The window grows to the length of the data, so the last call sees every row. The total work grows with the square of the data length. For a long series, a custom function over an expanding window can take minutes.
Look for a built-in or cumulative alternative first:
| You want | Slow approach | Faster approach |
|---|---|---|
| Running sum | `expanding().apply(np.sum, raw=True)` | `cumsum()` or `expanding().sum()` |
| Running maximum | `expanding().apply(np.max, raw=True)` | `cummax()` or `expanding().max()` |
| Running mean | `expanding().apply(np.mean, raw=True)` | `expanding().mean()` |
Compiling custom functions with Numba
When no built-in fits, apply can use Numba, a library that compiles Python functions to machine code. Install it first with pip install numba. Then pass engine="numba". This engine requires raw=True, because the compiled function works on arrays:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
s = pd.Series(rng.normal(size=200_000))
def spread(values):
return values.max() - values.min()
r = s.rolling(100)
first = r.apply(spread, raw=True, engine="numba")
second = r.apply(spread, raw=True, engine="numba")
print(first.equals(second))Two points explain how to read the timing of this code:
- The first call includes compile time. It can be slower than the plain
engine="cython"version. - Later calls reuse the compiled function and are much faster, as long as the function and settings stay the same. Passing
engine_kwargs={"cache": True}also saves the compiled code on disk between runs, which helps in scripts that start fresh each time.
Numba is therefore worth it when you call the same custom function many times or on large data. For a single call on a small series, the compile time can exceed the saving. Only a subset of Python and NumPy works inside a Numba function. If your function uses unsupported features, pandas raises a Numba error. In that case, rewrite the function more simply, or fall back to raw=True with the default engine.
Exponentially weighted windows as a cheap alternative
An exponentially weighted mean looks at all earlier values, but each result is computed from the previous result and the new value. The cost per row is constant, and it does not depend on a window length at all. For smoothing, s.ewm(span=100).mean() is much cheaper than a 100-row rolling apply with custom weights. If you only need a smooth trend that favors recent values, ewm is often both faster and simpler. If you need exact equal weights over a hard cutoff, it is not a substitute.
Smaller costs worth knowing
- Dtype conversion. Rolling aggregations compute in
float64. Integer columns are converted, which uses extra memory on large frames. Selecting only the columns you need before rolling avoids converting columns you will discard. - Memory for wide results.
aggwith a list on a DataFrame produces a column for each combination of input column and aggregation. A frame with 50 columns and 3 aggregations gives 150 columns. - Floating-point drift. Because built-ins update a running total, results can differ from a from-scratch calculation in the last few decimal places. Compare with
np.allclose, not==, when you check one method against another, as the earlier example does. min_periods,centerandclosed. These options change which rows are valid, not how much work is done. You do not need to avoid them for speed.
A decision path
The flowchart below summarizes the order in which to try options.
Measure before you optimize
Most window code is fast enough with built-ins, and rewriting it for speed has a cost in readability. A practical order of work:
- Write the clearest version using built-in aggregations.
- If it is too slow, time each step with
time.perf_counteror%timeit, so you know which call dominates. - Replace
applywith built-ins, then switch toraw=True, then try Numba. - Check that the faster version matches the clear one with
np.allclose.
Exercise
You have a sorted minute-level price Series with 2 million rows. You need the rolling range (max minus min) over 500 rows, and your current code uses s.rolling(500).apply(lambda w: w.max() - w.min()). Give two changes, in order of preference, that make it faster while keeping the same result.
Show answer
First, replace the apply with built-ins: r = s.rolling(500); r.max() - r.min(). This uses compiled code that updates each window incrementally. If a built-in version were not possible, the second change is to add raw=True to the apply call so each window is passed as a NumPy array instead of a new Series, and then optionally add engine="numba" with a named function. Check the results against the original on a small slice with np.allclose(..., equal_nan=True).
Exercise
A colleague calls df.rolling("7D").mean() on a DataFrame whose DatetimeIndex was built from several concatenated files. It raises a ValueError about the index. What is the cause, and what is the fix?
Show answer
A time-based window requires a monotonic index, and concatenating files can leave timestamps out of order. Call df = df.sort_index() once before rolling, then run df.rolling("7D").mean().
Exercise
Why is s.expanding().apply(func, raw=True) far more expensive than s.rolling(10).apply(func, raw=True) on the same long series?
Show answer
The rolling window always has 10 rows, so the work per row is fixed. The expanding window grows to include every earlier row, so the function sees more data at each step. The total work grows roughly with the square of the series length. Use a built-in such as expanding().mean() or a cumulative method such as cumsum() when one fits.