kmail.at
contact

elsewhere

EnglishEN
← learning

pandas · difficulty ◆

pandas query() — filter DataFrames with expression strings

Write the filter you mean — query() turns selection logic into one readable expression.

There is a line of pandas you have written a thousand times that never needed to be that ugly.

AI-generated draft · reviewed and editedThis text was generated with AI as a first draft, then reviewed and edited by the author, who holds editorial responsibility for it.

2026-08-28 · 5 min read

$ df.query()
0.13
added in pandas

January 2014

numexpr
default eval engine

optional dependency with real speedups on big frames

@name — since 0.13 (2014)
python variables

the pandas parser rewrites @name into a local reference; it shipped with query() in 0.13, not 0.25

What it does

query() filters the rows of a DataFrame using an expression string: df.query('pm25 > 15') keeps exactly the rows where the column pm25 exceeds 15. Inside the string, column names are plain identifiers — no df. prefix, no repeated bracket indexing. Compound logic is plain English: 'and', 'or', 'not', plus 'in' for membership. The string is re-parsed on every call and then handed to numexpr when it is installed, so the speed story is real but narrower than it looks — see the benchmark further down.

Why it matters

Filtering is the single most frequent DataFrame operation, and the bracket idiom df[(df.a > 1) & (df.b == 'x')] forces you to repeat the frame name, mind operator precedence (& vs and), and wrap every condition in parentheses. query() removes all of that noise: the expression reads like the question you are actually asking. It chains beautifully too — df.assign(...).query(...) builds transform-then-filter pipelines in one expression chain, and the @name syntax lets SQL-style variables reference Python values without string formatting.

When query() is the wrong tool

Three things are worth knowing before you rewrite every filter.

Measure first. On a million-row frame here (pandas 3.0.3, numexpr 2.14.2) the simple predicate 'a > 0.5 and b < 0.5' took 15.2 ms through query() and 4.5 ms through df[(df.a > 0.5) & (df.b < 0.5)] — query() re-parses the string on every call, and that parse is the whole difference. Add arithmetic and the order flips: (a**2 + b**2 - c**2) / (a + b + c) > 0.2 took 22.4 ms through query() and 30.5 ms through the hand-written mask, which is numexpr fusing the expression. Short hot predicate: keep the mask. Long arithmetic-heavy filter: query() pays for itself.

Quote awkward names. Any column whose name is not a valid Python identifier has to be backticked — df.query('`air quality index` > 50'). Without backticks you get a bare SyntaxError: invalid syntax rather than a helpful message.

Never interpolate user input. The method's own docstring carries the warning: query() "can run arbitrary code which can make you vulnerable to code injection if you pass user input to this function". Keep expressions in your source and pass data in through @name.

Example

$ df.query('pm25 > 15')
     city  pm25  year
0  Berlin    24  2024
1   Paris    19  2024
2    Rome    31  2025
3  Berlin    22  2025

Every row above the threshold, in one readable line.

$ avg = df.pm25.mean()   # 19.5
df.query('pm25 > @avg').city.tolist()
['Berlin', 'Rome', 'Berlin']

@references a Python variable — the @-prefix is the only escaping rule you need.

$ df.query("city == 'Vienna' and year == 2024")['pm25'].item()
12

Compound conditions with and / or read like plain English.

$ df.assign(pm25_norm=df.pm25 / df.pm25.max()).query('pm25_norm < 0.5').city.tolist()
['Vienna', 'Vienna']

Transform-then-filter in one chain: assign a computed column, filter on it, done.

$ thresholds = [12, 20]
df.query('pm25 > @thresholds[1]')['city'].tolist()
['Berlin', 'Rome', 'Berlin']

@ references the real Python object, not a formatted string, so subscripts work: @thresholds[1] is 20. That is why you never f-string a value into the expression.

Common flags

df.query('col > 5')
basic comparison: > >= < <= == != on any column
'a and b', 'a or b', 'not a'
combine conditions with words instead of & | ~
'city in ["Vienna", "Rome"]'
membership test; also 'not in'
'pm25 > @avg'
@name references a local Python variable inside the expression
inplace=True
modify the DataFrame in place instead of returning a copy (defaults to False)
engine='python'
force the plain-Python evaluator; leaving engine unset picks numexpr when it is installed and falls back to plain Python when it isn't
parser='pandas'|'python'
'pandas' (the default) is the small dialect that understands @name, backticks and and/or/not; parser='python' enforces strict Python parsing, where @ raises SyntaxError ("The '@' prefix is only supported by the pandas parser") and 'and' raises NotImplementedError

History

Added in pandas 0.13 (January 2014)

query() arrived as a top-level DataFrame method wrapping the numexpr evaluation engine, giving pandas a fast, readable path for medium-to-large boolean selections. It was pitched from the start as the readable alternative to the mask idiom — 'SQL-like' selection for people who think in predicates rather than in array algebra.

The @-syntax (pandas 0.13, 2014)

@name has been part of the expression language since the very beginning: pandas 0.13 shipped query(), eval() and the pandas parser together, and pandas/computation/expr.py in 0.13.0 already rewrites '@a' into a local reference before parsing. What 0.25 (2019) added later were the comfort features — backticked column names (GH 6508) and keyword arguments for a callable local reference (GH 26426). Alongside eval() — its sibling method for column arithmetic — query() is the reason pandas speaks a small expression language at all.

Under the hood

Under the hood: from string to bytes

When you call query(), pandas tokenizes the expression, resolves each identifier against the DataFrame's columns (backtick-quoted names for awkward identifiers), and then hands the compiled expression to numexpr — a C++ engine that fuses the whole predicate into one pass over the arrays. If numexpr is not installed, pandas falls back to plain Python evaluation; the results are identical, only the speed differs. The same machinery powers eval(), which is why the two methods share dialect rules like the @-prefix.

Fun facts

Pros & cons

pros

  • + Reads like the question you are asking — filters stay readable at any complexity
  • + numexpr acceleration on arithmetic-heavy predicates, with nothing extra to write
  • + Chains cleanly with assign() and eval() into one-line pipelines

cons

  • − String expressions get no IDE type-checking or autocomplete
  • − Awkward column names (spaces, leading digits) need backtick quoting
  • − inplace=True is discouraged by the pandas team — prefer assigning the result

Takeaways

  1. 1Reach for query() whenever a filter reads like a sentence — it stays readable where brackets collapse into noise
  2. 2Inject Python values with @var; never f-string numbers into the expression string
  3. 3'in' / 'not in' work inside expressions — often cleaner than .isin()
  4. 4Chain assign() → query() for transform-then-filter in a single statement
  5. 5Skip inplace=True; assign the result instead — that is where pandas is heading

Related commands

← all learning