Sub topic 12
eval, query, and Numba for remaining hot spots
This chapter covers the last tools to try after the usual fixes are done. It assumes you can read a cProfile report, know how to vectorize column arithmetic with NumPy-style expressions, and have already checked your results against the original code. You should also be comfortable with Python functions and decorators. Earlier chapters showed that most slow pandas code is fixed by removing row loops, choosing better dtypes, and loading less data. Start there. Use the tools below only when the profile still shows one step dominating and that step is already vectorized or cannot be vectorized.
Where these tools fit
Both tools attack a different cost.
DataFrame.evalandDataFrame.querytake an expression as a string. When the optionalnumexprpackage is installed, pandas can evaluate a large expression in one pass over the data instead of creating one temporary array per operator.- Numba is a compiler. Its
@njitdecorator turns a Python function that works on NumPy arrays into machine code the first time you call it. This makes explicit loops fast, which is useful when each step depends on the previous one.
eval: fewer temporary arrays
Consider the expression (a * b + c ** 2) / (1 + a). Written with ordinary pandas operators, each operator allocates a full-length temporary array: one for a * b, one for c ** 2, one for the sum, and so on. On millions of rows, that memory traffic costs more than the arithmetic. With numexpr installed (pip install numexpr), eval compiles the whole expression and evaluates it in cache-sized blocks, using several threads.
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({
"a": rng.random(n),
"b": rng.random(n),
"c": rng.random(n),
})
start = perf_counter()
plain = (df["a"] * df["b"] + df["c"] ** 2) / (1 + df["a"])
print(f"operators: {perf_counter() - start:.3f}s")
start = perf_counter()
fast = df.eval("(a * b + c ** 2) / (1 + a)")
print(f"eval: {perf_counter() - start:.3f}s")
np.testing.assert_allclose(plain.to_numpy(), fast.to_numpy())The check uses assert_allclose instead of exact equality because numexpr may order floating-point operations differently and differ in the last bit. Run the timing a few times; the first call includes import and setup cost.
eval can also assign columns. The result is a new frame unless you pass inplace=True:
df = df.eval("score = (a * b + c ** 2) / (1 + a)")When eval does not help
- Small frames. Parsing the string has a fixed cost. Below roughly 10,000 rows, plain operators are usually faster. The break-even point depends on the machine, so measure it.
- Simple expressions.
df["a"] + df["b"]is already a single pass.evalgains nothing. - No numexpr. Without it, pandas falls back to a Python engine. The code still runs but is not faster.
- Unsupported operations.
evalhandles arithmetic, comparisons, and boolean logic. Arbitrary function calls, string methods, andgroupbyare outside its scope.
query: filtering with a readable expression
query applies the same machinery to row filtering. It returns the same rows as a boolean mask does, and it often reads more clearly when there are several conditions.
threshold = 0.9
subset = df.query("a > @threshold and b < 0.1")
same = df[(df["a"] > threshold) & (df["b"] < 0.1)]
pd.testing.assert_frame_equal(subset, same)Details that cause errors:
- Use
@nameto refer to a Python variable. Without the@, pandas looks for a column callednameand raisesUndefinedVariableErrorif there is none. - Column names that are not valid identifiers need backticks, as in `
df.query("unit price> 5")`. - Inside the string, use
and,or,not, or the symbols&,|,~. Plain Pythonandworks here but not in a boolean mask. - Do not build query strings from untrusted input. The string is parsed and evaluated, so treat it like code.
The speed gain of query over a mask is real only for large frames and several conditions. Choose it mostly for clarity, and expect a speedup as a bonus.
Numba: loops that cannot be vectorized
Some computations are sequential. Each result depends on the previous result, so no single column operation expresses them. A common example is a balance that is clipped to a range after every step:
balance[i] = min(max(balance[i-1] + delta[i], 0), cap)Cumulative sum followed by clipping gives the wrong answer here, because clipping at step i changes every later value. A Python loop is correct but slow. Numba keeps the loop and compiles it.
import numpy as np
import pandas as pd
from time import perf_counter
from numba import njit
@njit
def capped_balance(deltas, cap):
out = np.empty_like(deltas)
balance = 0.0
for i in range(deltas.shape[0]):
balance = balance + deltas[i]
if balance < 0.0:
balance = 0.0
elif balance > cap:
balance = cap
out[i] = balance
return out
rng = np.random.default_rng(0)
events = pd.DataFrame({"delta": rng.normal(0.0, 1.0, 1_000_000)})
values = events["delta"].to_numpy()
capped_balance(values[:10], 50.0) # warm-up call: triggers compilation
start = perf_counter()
events["balance"] = capped_balance(values, 50.0)
print(f"numba: {perf_counter() - start:.4f}s")
start = perf_counter()
reference = capped_balance.py_func(values, 50.0)
print(f"python: {perf_counter() - start:.4f}s")
np.testing.assert_allclose(events["balance"].to_numpy(), reference)The py_func attribute is the original uncompiled function, so the reference result comes from exactly the same logic. Expect the compiled call to be tens to hundreds of times faster than the Python loop.
How Numba behaves
- Compilation happens on the first call. It takes from a fraction of a second to several seconds. Time a warm-up call separately, as above, or your benchmark will measure the compiler.
- Compiled code is specialized by argument types. Calling the function with
float32afterfloat64compiles it again. Keep dtypes consistent. - Pass NumPy arrays, not DataFrames. Use
.to_numpy()on columns. Numba does not understandSeries,DataFrame, or the index. You reattach the result by assigning it back, which assumes the same row order. @njitmeans no Python fallback. If Numba cannot compile something, it raisesTypingErrorinstead of silently running slowly. That is the behavior you want.- Object columns do not work. Strings stored as Python objects, mixed types, and most pandas extension arrays fail. Convert to numeric arrays first, for example by factorizing a category into integer codes.
- Missing values need a plan. A float column with
NaNworks, and comparisons withNaNare false. A nullable integer column (Int64) must be converted first, for example with.to_numpy(dtype="float64", na_value=np.nan).
Numba also integrates directly with a few pandas methods. rolling(...).apply(func, raw=True, engine="numba") compiles func for you. It requires raw=True so the function receives NumPy arrays. Try this before writing your own loop if the sequential step is a custom rolling window.
Choosing between the options
| Situation | Try first | Why |
|---|---|---|
| Long arithmetic expression, millions of rows | `eval` | Avoids temporary arrays and uses several threads |
| Several filter conditions, large frame | `query` or a boolean mask | Same speed class; `query` reads better |
| Each row depends on earlier rows | Numba `@njit` | The loop cannot be written as column operations |
| Custom function over rolling windows | `rolling.apply(..., engine="numba")` | Compiles for you |
| Strings, dates, or mixed objects | Vectorized `.str` and `.dt` methods | Numba cannot compile these types |
| Frame under about 10,000 rows | Plain pandas | Fixed overheads outweigh any gain |
Costs to weigh
- Dependencies.
numexprandnumbaare extra packages. Numba is tied to specific NumPy versions, so an upgrade can break an environment. - Maintainability. A reader must know that a string is code, or that a decorated function has typing rules. Add a comment saying what was measured and which speedup it gave.
- Debugging. Errors from compiled code are harder to read. Develop the function in plain Python first, check it against test data, then add
@njit. - Deployment. The first-call compile delay matters in short-lived scripts. Numba can cache results to disk with
@njit(cache=True), which helps repeated runs of the same script.
Workflow summary
- Profile and identify the one step that dominates.
- Make sure it is already vectorized as far as plain pandas allows.
- Choose
evalorqueryfor large expressions and filters, or Numba for sequential logic. - Warm up, then time with
perf_counteron realistic data sizes. - Compare results with
assert_allcloseorassert_frame_equal. - Keep the change only if the gain is large enough to justify the added dependency.
Exercise
A pipeline computes a running total that resets to zero whenever the previous total exceeds a limit. You profile it and find the Python loop takes 90% of the time. A colleague suggests df.eval(...). Why will eval not work here, what would you use instead, and what two steps do you take before trusting the timing and result?
Show answer
eval only handles element-wise expressions over columns. A running total that resets depends on its own previous value, so it cannot be written as a single column expression. Use a Numba @njit function that loops over a NumPy array (from .to_numpy()) and carries the total in a local variable. Before trusting it, call the function once on a small slice to trigger compilation, so the timing measures only compiled code. Then compare its output with the original Python version, for example through py_func and np.testing.assert_allclose, to confirm the results match.
Exercise
You run df.query("price > limit") and get UndefinedVariableError: name 'limit' is not defined. limit is a Python variable you set earlier. What is the fix?
Show answer
Write df.query("price > @limit"). Without the @, pandas looks for a column named limit, finds none, and raises the error.