skip to content

In pandas DataFrame.query, how do you compare a column with a Python variable and refer to a column named 'trip km'?

level: middleimportance: should knowfreq 50%

answer

  1. bare names mean columns
  2. a prefix character for locals
  3. quoting non-identifier column names
  4. UndefinedVariableError

basics

~20 s

Inside a DataFrame.query string, prefix a Python variable with @ (fare > @min_fare) and wrap a column name that is not an identifier in backticks (trip km > 3); a bare name always means a column.

solid answer

~30 s

In `query` and `DataFrame.eval` a bare name is a column, so a Python variable needs `@`: `trips.query("fare > @min_fare and city in @cities")`. Without it pandas raises `UndefinedVariableError`, unless a column has the same name, in which case the bare name silently means the column. A column such as `trip km` that is not a valid identifier goes in backticks: ``trips.query("`trip km` > 3")``. The default `parser="pandas"` gives `&` and `|` the precedence of `and` and `or`, so no extra parentheses are needed. Never format user input into the string; both methods can run arbitrary code.

code

python · 14 lines
python
import pandas as pd

trips = pd.DataFrame({
    "city": ["Lyon", "Oslo", "Lyon", "Pune"],
    "fare": [12.0, 30.0, 8.0, 5.0],
    "trip km": [3.0, 12.0, 2.0, 4.0],
})
min_fare = 6
cities = ["Lyon", "Pune"]

print(trips.query("fare > @min_fare and city in @cities"))
print(trips.query("`trip km` > 3"))
print(trips.eval("fare_per_km = fare / `trip km`").columns.tolist())
print(trips.columns.tolist())

go deeper

for a junior

Recall the two syntaxes: @name for a Python variable and backticks around a column name with spaces or punctuation.

for a middle

Explain the lookup rule, bare names are columns, the UndefinedVariableError without @, and the pandas parser's precedence for & and |.

for a senior

Point out the silent failure when a variable and a column share a name, and refuse to format user input into a query string.

for a principal

Decide where string expressions are allowed in team code: fine for readable filters in trusted pipelines, never for anything a user can influence.

## `query` and `eval`: column expressions as strings `DataFrame.query(expr)` keeps the rows for which a **boolean expression written as a string** is true; `DataFrame.eval(expr)` evaluates a string expression over the columns and returns the result, or, when the string contains an assignment such as `"total = fare + tip"`, returns a **copy of the frame with that column added**. Both suit method chains because they need no reference to the frame's variable name: `query("fare > 6")` reads `fare` from whatever frame it is called on. Inside the string, a **bare name means a column** of that frame (the index can be referred to as `index` or by its name). Everything else needs explicit syntax. ## Referring to Python variables with `@` A local Python variable must be prefixed with **`@`**: ```python min_fare = 6 cities = ["Lyon", "Pune"] trips.query("fare > @min_fare and city in @cities") ``` - Forgetting the `@` raises `UndefinedVariableError` (a subclass of `NameError`, from `pandas.errors`) with the message that the name is not defined, as long as no column has that name. - If a **column and a variable share a name**, the bare name is the column and `@name` is the variable, so `"fare > @fare"` compares the column with the variable. This is the case where a missing `@` does not fail at all: `"fare > fare"` silently compares the column with itself and returns no rows. - `in` and `not in` work against a list held in a variable (`city in @cities`), and `==` against a list behaves like `isin` in a query string. - Variables are looked up in the scope where `query` was called. When `query` runs inside a function handed to `pipe`, `@min_km` is that function's local or argument. ## Column names that are not identifiers: backticks A column whose name is not a valid Python identifier, because it contains a space or punctuation or starts with a digit, must be wrapped in **backticks**: ```python trips.query("`trip km` > 3") trips.eval("fare / `trip km`") ``` The `DataFrame.eval` docstring adds that column names which are Python keywords (`if`, `for`, `import`) cannot be used in an expression. Renaming such columns early in the chain, with `rename` or `set_axis`, keeps later strings simple. ## The `'pandas'` parser and operator precedence By default both methods use `parser="pandas"`, which changes one thing a Python reader expects: | Expression | Plain pandas indexing | Inside `query` (default parser) | |---|---|---| | `fare > 6 & tip > 0.5` | `&` binds tighter than `>`, so it fails or misreads without parentheses | `&` has the precedence of `and`, so it reads as intended | | `fare > 6 and tip > 0.5` | `and` on two Series raises the ambiguous truth value error | supported, same as `&` | | `5 < fare < 20` | not supported on Series | supported chained comparison | Passing `parser="python"` restores strict Python precedence. The `engine` argument (default `None`: use numexpr if installed, else Python) changes speed, not the result. ## `eval` inside a chain `DataFrame.eval` follows the same name rules and adds assignment: - an expression without `=` returns the computed result, usually a Series: ``trips.eval("fare / `trip km`")``; - an expression with `=` returns a **new frame** with the column added or overwritten, and leaves the original unchanged, so it can sit in a chain like `assign`; - a multi-line string can assign several columns at once, each line able to use the columns created above it; - `inplace=True` modifies the frame and returns `None`, which ends a chain. ## Things that go wrong in a chain 1. **A missing `@`** on a name that is also a column: no error, wrong filter. 2. **An f-string instead of `@`**: `query(f"city == '{name}'")` works until a value contains a quote, and it pastes data into code. The `query` and `eval` docstrings warn that both can run arbitrary code and are a **code-injection risk if passed user input**; build masks with `loc` for anything a user typed. 3. **`inplace=True`** on `query` or `eval` returns `None`, ending the chain. 4. Expecting `eval` to accept arbitrary function calls: only arithmetic, comparisons, boolean operators, attribute access, subscripts and a fixed list of math functions are allowed, with no lambdas or comprehensions. ## What a good answer includes Name `@` for variables and backticks for awkward column names, the `UndefinedVariableError` you get without `@`, the column-wins rule when names collide, the parser's `&`/`and` precedence, and the injection warning. Mentioning that `eval` with an assignment returns a new frame rather than mutating the original shows you know why it sits comfortably inside a chain.

  • What happens if a variable and a column share a name and you forget the @ in pandas query?
    The bare name resolves to the column, so no error is raised. With a variable `fare = 100`, `trips.query("fare > fare")` compares the column with itself and returns an empty frame, while `"fare > @fare"` compares the column with 100. That silent case is why a review should check every bare name in a query string against the frame's columns.
  • Why is trips.query(f"city == '{user_city}'") a problem in a web service?
    It pastes data into an expression string that pandas parses and evaluates, and the `query` and `eval` docstrings warn they can run arbitrary code, so user input becomes an injection risk. It also breaks on a value containing a quote. Use `@user_city` for trusted code, and for anything a user supplied build the mask in plain Python with `loc` instead of a string.

  • In query, a bare name is looked up as a Python variable first
  • Column names with spaces cannot be used in query at all
  • An f-string is the normal way to put a variable into query
  • query needs parentheses around each comparison joined by &
  • DataFrame.eval with an assignment modifies the original frame