Sub topic 12
eval, query, and Numba for remaining hot spots
This chapter assumes you have already measured your code with perf_counter and cProfile. It also assumes you have replaced row loops with vectorized operations. If a profile still shows one arithmetic-heavy step or one sequential loop dominating the run time, the tools here are the next option. They are not a first fix.
What eval and query do
A vectorized expression such as a * b + c creates a temporary array for a * b, then another for the sum. On large frames, those temporaries cost memory and time. DataFrame.eval takes the expression as a string and, when the optional numexpr package is installed, evaluates it in chunks without full-size temporaries. Without numexpr, pandas falls back to ordinary evaluation, so the code still runs but the speedup disappears.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
n = 2_000_000
df = pd.DataFrame({
"price": rng.random(n),
"qty": rng.integers(1, 10, n),
"tax": rng.random(n) * 0.2,
})
start = perf_counter()
plain = df["price"] * df["qty"] * (1 + df["tax"])
print(f"plain: {perf_counter() - start:.3f}s")
start = perf_counter()
fast = df.eval("price * qty * (1 + tax)")
print(f"eval: {perf_counter() - start:.3f}s")
print(np.allclose(plain, fast))eval can also assign a new column in the same call: df.eval("total = price * qty", inplace=True).
DataFrame.query applies the same engine to row filters. Use @ to refer to a Python variable.
threshold = 0.5
subset = df.query("qty >= 5 and price > @threshold")query mostly improves readability. Its speed gain appears only on large frames with several combined conditions.
What Numba does
Some work cannot be vectorized because each step depends on the previous one. Examples are running maximums that reset on a condition, state machines, and path-dependent calculations. For these, a Python loop is slow, but a loop compiled to machine code is fast. Numba is a library that compiles Python functions with the @njit decorator.
Numba works on NumPy arrays and plain numbers, not on DataFrames or Series. Extract the data with to_numpy() first.
import numpy as np
import pandas as pd
from time import perf_counter
from numba import njit
@njit
def max_drawdown(values):
peak = values[0]
worst = 0.0
for v in values:
if v > peak:
peak = v
drawdown = (peak - v) / peak
if drawdown > worst:
worst = drawdown
return worst
rng = np.random.default_rng(0)
prices = 1.0 + rng.random(2_000_000)
series = pd.Series(prices)
start = perf_counter()
max_drawdown(series.to_numpy())
print(f"first call (includes compile): {perf_counter() - start:.3f}s")
start = perf_counter()
max_drawdown(series.to_numpy())
print(f"second call: {perf_counter() - start:.3f}s")The first call includes compilation time. Time the second and later calls when you compare against a pure Python loop.
Choosing between them
| Tool | Best for | Main cost |
|---|---|---|
| `eval` | Long arithmetic expressions on large frames | Limited syntax, small gain on small data |
| `query` | Readable filters with several conditions | String-based, harder to debug |
| Numba | Sequential loops that cannot be vectorized | Extra dependency, compile time, limited Python support |
Common errors
- Passing a DataFrame into an
@njitfunction. Numba raises a typing error. Passto_numpy()arrays. - Timing the first Numba call and concluding it is slow.
- Using
evalwith column names that contain spaces, without wrapping them in backticks. - Skipping the result check. Compare outputs with
np.allcloseorpd.testing.assert_series_equal, as you did in the earlier chapter on verifying results.
Exercise
A step computes a running balance where each row's value depends on the previous row's result and a reset rule. Vectorizing it is not possible. Which tool fits, and what must you do to the data before calling the function?
Show answer
Use Numba with @njit, because the rows depend on each other. Convert the needed columns with to_numpy() before calling the function, since Numba cannot work with DataFrames. Time the second call so compile time is excluded.