ZetCode

Pandas query Function

last modified November 17, 2026 Python 3.15

The DataFrame.query method selects rows with a condition written as a string. Instead of repeating the DataFrame name inside the condition, we name the columns directly, which often makes filtering easier to read.

All examples use the same small DataFrame and were verified with pandas 3.1.1. We also look at filter, a related method that selects columns by name rather than rows by value.

Simple expressions

A simple expression compares a column with a number. The string 'age > 28' is evaluated once for every row, and only the rows for which it is true are kept. The original index labels are preserved, so the returned row still shows label 1.

query_simple.py
import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Cindy'], 'age': [25, 32, 28]})
print(df.query('age > 28'))

Only Bob, aged 32, satisfies the condition. Alice at 25 and Cindy at 28 do not, so they are left out of the result.

$ python query_simple.py
  name  age
1  Bob   32

String conditions

String values inside the query must be quoted. Use one kind of quote for the outer Python string and the other kind for the value inside, as in "name == 'Bob'". The in operator tests membership in a list, keeping rows whose value is one of the listed strings.

query_string.py
import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Cindy'], 'city': ['Prague', 'Vienna', 'Prague']})
print(df.query("name == 'Bob'"))
print()
print(df.query("city in ['Prague', 'Vienna']"))

The first query matches one row by name. The second asks for cities in the given list; here every row matches because the only cities are Prague and Vienna.

$ python query_string.py
  name    city
1  Bob  Vienna

    name    city
0  Alice  Prague
1    Bob  Vienna
2  Cindy  Prague

External variables with @

A variable defined in the surrounding Python code can be used in a query by prefixing its name with @. This is useful when the threshold comes from user input or a calculation instead of being hard-coded.

query_at.py
import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Cindy'], 'age': [25, 32, 28]})
limit = 28
print(df.query('age >= @limit'))

The @limit marker tells pandas to read the Python variable limit, which is 28, so Bob and Cindy are returned. Changing the variable changes the selection without editing the expression.

$ python query_at.py
    name  age
1    Bob   32
2  Cindy   28

Comparison with boolean indexing

Boolean indexing selects rows by giving a list of true or false values, one per row, inside square brackets. It is the most direct way to filter a DataFrame. Compare the two forms below: they produce the same rows, but query avoids repeating the DataFrame and column names.

query_boolean.py
import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Cindy'], 'age': [25, 32, 28]})
print(df.query('age > 28'))
print()
print(df[df['age'] > 28])

Both forms return Bob's row. Use whichever reads more clearly in context; boolean indexing is covered in more depth in the Pandas boolean indexing tutorial.

$ python query_boolean.py
  name  age
1  Bob   32

  name  age
1  Bob   32

numexpr and Python engines

The engine parameter chooses how the expression is evaluated. numexpr is an optional accelerator that compiles numeric expressions for speed; python is the built-in fallback, which handles a wider range of objects. Both are shown below and agree on the result.

query_engines.py
import pandas as pd

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Cindy'], 'age': [25, 32, 28]})
print(df.query('age > 28', engine='numexpr'))
print()
print(df.query('age > 28', engine='python'))

The two blocks of output are identical. Pandas picks an engine automatically when you omit the parameter; specify engine='python' if an expression uses features that numexpr does not support, and install the numexpr package if you want the faster engine available.

$ python query_engines.py
  name  age
1  Bob   32

  name  age
1  Bob   32

Selecting columns with filter

While query filters rows by their values, filter selects columns by their names. With items we list exact names, with like we match a substring, and with regex we use a regular expression, a compact pattern language for describing text — here ^a means a name starting with a.

query_filter.py
import pandas as pd

df = pd.DataFrame({
    'name': ['Alice', 'Bob'],
    'age': [25, 32],
    'city': ['Prague', 'Vienna']
})

print(df.filter(items=['name', 'age']))
print()
print(df.filter(like='i'))
print()
print(df.filter(regex='^a'))

The first result lists the two requested columns. The second keeps only city, the sole column name containing the letter i. The third keeps age, the only name starting with a.

$ python query_filter.py
    name  age
0  Alice   25
1    Bob   32

     city
0  Prague
1  Vienna

   age
0   25
1   32

Limits with column names containing spaces

A column name with a space is not a valid Python identifier, so writing it bare inside a query is parsed as an error. Surround such a name with backticks to tell pandas it is a column name. The error type is caught and printed below so you can see both cases.

query_spaces.py
import pandas as pd

df = pd.DataFrame({'first name': ['Alice', 'Bob'], 'age': [25, 32]})
try:
    print(df.query('first name == "Alice"'))
except Exception as e:
    print('plain expression:', type(e).__name__)

print('\nwith backticks:')
print(df.query('`first name` == "Alice"'))

The bare expression raises a SyntaxError. Wrapping the name in backticks makes the same condition work and returns Alice's row. The cleanest solution is usually to rename columns to identifiers without spaces before querying them.

$ python query_spaces.py
plain expression: SyntaxError

with backticks:
  first name  age
0      Alice   25

Source

Pandas DataFrame.query Documentation, Pandas DataFrame.filter Documentation, and Pandas Indexing and selecting data Documentation

In this article we have filtered rows with query, used string and variable values, compared it with boolean indexing, tried both evaluation engines, selected columns with filter and handled column names with spaces. For more ways to select data see the boolean indexing tutorial and the Pandas loc tutorial.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pandas tutorials.