query() lets you write a filter condition as readable text, like a string combining several comparisons with 'and'/'or', instead of the more verbose bracket-and-boolean-array syntax with & and parentheses around each comparison — internally, it parses the string expression and evaluates it against the DataFrame's columns, referencing external Python variables by prefixing them with @. For very large DataFrames, query(), and the related eval(), can also be noticeably faster than the equivalent bracket-based filtering, since it can avoid building some intermediate boolean arrays.
1Understanding df.query()
query() lets you write a filter condition as readable text, like a string combining several comparisons with 'and'/'or', instead of the more verbose bracket-and-boolean-array syntax with & and parentheses around each comparison — internally, it parses the string expression and evaluates it against the DataFrame's columns, referencing external Python variables by prefixing them with @. For very large DataFrames, query(), and the related eval(), can also be noticeably faster than the equivalent bracket-based filtering, since it can avoid building some intermediate boolean arrays.
Prefix an external Python variable with @ inside a query() string to reference it — without the @, query() would look for a column with that same name instead of the variable.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob", "Carol"], "age": [30, 25, 35]})
print(df.query("age > 28"))2Practical Example
Here is a real-world application of df.query() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob", "Carol"], "age": [30, 25, 35]})
min_age = 28
print(df.query("age > @min_age"))3Best Practices
Follow these guidelines when working with df.query():
1. Use query() for filters with multiple conditions, since the string syntax is often more readable than chained boolean-indexing with & and parentheses everywhere
2. Prefix external variables with @ inside the query string, to distinguish them from column names
3. Prefer plain boolean indexing over query() for very simple, single-condition filters, where the string-expression overhead isn't worth it
Tip: Prefix an external Python variable with @ inside a query() string to reference it — without the @, query() would look for a column with that same name instead of the variable.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob", "Carol"], "age": [30, 25, 35]})
print(df.query("age > 28"))