pandas · difficulty ◆◆
pandas eval() — build columns from formula strings
Write the formula once, not the column four times.
Half the ugly pandas code I delete is just `df['a']` repeated eight times inside one arithmetic expression.
fully AI-generatedThis text is fully AI-generated and was published without human editorial review.$ df.eval()- 0.13.0
- Introduced
- 2
- Named parameters
- 2
- Engines
- no speedup
- Docs verdict on engine='python'
pandas changelog, January 2014 — flagged experimental at the time
signature is eval(expr, *, inplace=False, **kwargs); engine, parser, local_dict, global_dict ride in kwargs
'python' and 'numexpr'; numexpr is an optional dependency
pandas user guide: you will achieve no performance benefits using engine='python'
What it does
eval() takes a Python expression as a string, parses it, and runs it against the DataFrame's columns. You can read columns by bare name (`price * qty`), reference Python variables with @, and create new columns with `=` inside the string. The return value is a new object (or None with inplace=True). Two engines sit underneath: 'numexpr', a chunked arithmetic evaluator, and 'python', which walks the AST and does the obvious thing with pandas objects.
Why it matters
Pricing, margin, and scoring formulas arrive as formulas — from a finance spreadsheet, a SQL view, a spec document. eval() lets you paste the shape of that formula into pandas almost verbatim, so the code still looks like the thing it implements. It also collapses multi-column derivation into one call, which means one place to read, one place to fix.
Example
$ import pandas as pd
orders = pd.DataFrame({
"region": ["EMEA", "APAC", "EMEA", "AMER", "APAC"],
"price": [120.0, 80.0, 45.5, 300.0, 15.0],
"qty": [3, 5, 10, 2, 40],
"discount": [0.10, 0.0, 0.25, 0.15, 0.0],
})
orders = orders.eval("revenue = price * qty * (1 - discount)")
print(orders) region price qty discount revenue
0 EMEA 120.0 3 0.10 324.00
1 APAC 80.0 5 0.00 400.00
2 EMEA 45.5 10 0.25 341.25
3 AMER 300.0 2 0.15 510.00
4 APAC 15.0 40 0.00 600.00The assignment happens inside the string. Without inplace=True the original frame is untouched — I verified `'revenue' in orders.columns` was still False, so rebind the result.
$ vat = 0.2
enriched = orders.eval("""
revenue = price * qty * (1 - discount)
net = revenue / (1 + @vat)
""")
print(enriched[["region", "revenue", "net"]]) region revenue net
0 EMEA 324.00 270.000000
1 APAC 400.00 333.333333
2 EMEA 341.25 284.375000
3 AMER 510.00 425.000000
4 APAC 600.00 500.000000Newline-separated assignments run in order, and the second expression can see `revenue` defined by the first. @vat pulls the Python float in from outside.
$ orders = orders.eval("revenue = price * qty * (1 - discount)")
big_emea = orders[orders.eval("revenue > 300 and region == 'EMEA'")]
print(big_emea) region price qty discount revenue
0 EMEA 120.0 3 0.10 324.00
2 EMEA 45.5 10 0.25 341.25eval() returns a boolean Series, so it drops straight into a mask. `and` / `or` work as words here — no parentheses-and-ampersand dance.
$ target = 400
print(orders.eval("revenue.mean()"))
print(orders.eval("revenue > @target").sum())435.05
2Reductions are allowed: mean over a column, and a count of rows above a threshold carried in through @.
$ q = pd.DataFrame({"order id": [1, 2], "unit price": [9.5, 20.0], "qty": [4, 3]})
print(q.eval("total = `unit price` * qty")) order id unit price qty total
0 1 9.5 4 38.0
1 2 20.0 3 60.0Column headers with spaces go in backticks. `order id` is never mistaken for a subtraction, and you skip the rename-first ritual.
Common flags
- expr
- The expression string; `=` inside it assigns columns instead of returning them.
- inplace=True
- Writes into the frame and returns None — the only way eval() mutates in place.
- engine="numexpr"
- Chunked arithmetic backend; raises ImportError if the optional numexpr package is missing. Default is picked automatically.
- engine="python"
- AST walker over pandas objects. Slower per the docs, and the honest choice when you want no surprises.
- @name
- Reference a Python variable from inside the string. Without the @, a column with that name wins.
- `unit price`
- Backticks escape column names that aren't valid Python identifiers.
- parser="python"
- Uses Python's own ast parser instead of pandas' — I confirmed it rejects backtick column names, so 'pandas' (the default) is the more capable grammar.
History
January 2014, labelled experimental
pandas 0.13.0 shipped pd.eval() and DataFrame.eval() as experimental features, alongside query(). The release notes are blunt about the mechanism: the new eval() function implements expression evaluation using numexpr behind the scenes. The pitch was arithmetic over big frames without building a temporary array per operator.
Why the string grammar is not Python
eval() grew its own parser because it had to know which names are columns. That is how bare `price` resolves to df["price"], and why the syntax is Python-shaped but narrower: no lambdas, no if/else expressions, no statements, one expression per call. The grammar is the price of the ergonomics.
Under the hood
What numexpr actually does with your string
pandas parses the expression into an AST, then hands the arithmetic part to numexpr as bytecode. numexpr walks contiguous NumPy buffers in cache-sized chunks, so `a + b * c` becomes one fused pass over memory instead of one temporary array per operator — that fused loop is the entire promise. String and datetime parts can't go through numexpr at all; the pandas docs say plainly that expressions producing object dtype or touching NaT get evaluated in Python space, while the numeric side still runs in numexpr. That split is why the win depends on your dtype mix, and why on a modern pandas my own measurement went the other way.
Fun facts
Pros & cons
pros
- + Formulas read like the spec: `revenue * (1 - discount)` with no df["..."] noise.
- + Several derived columns in a single call, with later lines seeing earlier assignments.
- + Column names with spaces work via backticks, so you don't rename just to compute.
cons
- − Not a reliable speedup on modern pandas — I measured it slower than plain operators.
- − Its own grammar: no lambdas, no if/else, no statements, and a semicolon gets you SyntaxError.
- − Silent shadowing: a column named like your variable wins unless you write @.
Takeaways
- 1Bind the result: `df = df.eval("x = ...")` — without inplace the assignment is thrown away.
- 2Reach for @ the moment a threshold or rate lives in a Python variable.
- 3Use newline-separated assignments when derived columns depend on each other.
- 4Keep eval() for numeric and boolean work; strings belong in .str or plain Python.
- 5Benchmark before you believe the numexpr story — measure your own frame.
Related commands
archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →
