query() (Pandas)

df.query() filters a DataFrame using a string expression, letting you write the condition in a compact, SQL-like form such as "age > 30 and city == 'NYC'" instead of repeating the DataFrame name.

Pandas

query() evaluates its string against the columns, which you reference by bare name. This keeps complex filters far more readable than chains of df['a'] & df['b'] comparisons, and you can splice in Python variables by prefixing them with @, as in df.query('age > @cutoff').

It supports and/or/not as words (not just &/|), in and not in for membership, and chained comparisons like '0 < x < 10'. Column names with spaces or special characters need backticks around them.

Under the hood query can use the numexpr engine, which can be faster on very large frames, though for small data the plain boolean-indexing form is usually quicker because it skips the string parsing.

Syntax

df.query('expression')

Examples

Python

import pandas as pd
df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
print(df.query("x > 1"))

Output:

   x  y
1  2  5
2  3  6

Learn it in a lesson

See also

Back to the Dictionary