The query() Method
Write readable filter expressions as strings with query(), use Python variables inside queries with @, and chain filters.
Why Use query()?
Pandas boolean indexing is powerful but can become verbose when combining many conditions. The query() method lets you write filter expressions as plain strings, which many people find more readable — especially those coming from a SQL background. Instead of df[(df['age'] > 30) & (df['salary'] > 50000)], you write df.query('age > 30 and salary > 50000').
The query string is evaluated against the column names of the DataFrame, so column names act like variable names inside the string.
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Carol', 'Dave'],
'age': [25, 35, 28, 45],
'salary': [50000, 90000, 70000, 120000]
})
# Boolean indexing style
result1 = df[(df['age'] > 27) & (df['salary'] > 60000)]
# Equivalent query() style
result2 = df.query('age > 27 and salary > 60000')
print(result2)
# name age salary
# 1 Bob 35 90000
# 2 Carol 28 70000Syntax Rules Inside a Query String
Inside a query string you can use standard Python comparison operators (>, <, ==, !=, >=, <=) and logical connectors and, or, not. Unlike regular boolean indexing, you can use the English words here — no ampersands or pipes needed.
Column names with spaces or that clash with Python keywords must be wrapped in backticks: df.query('`first name` == "Alice"').
import pandas as pd
df = pd.DataFrame({
'product': ['A', 'B', 'C', 'D'],
'price': [10, 200, 50, 300],
'in_stock': [True, False, True, True]
})
# Use 'and', 'or', 'not' in query strings
result = df.query('price > 40 and in_stock == True')
print(result)
# product price in_stock
# 2 C 50 True
# 3 D 300 True