Module 2 · Beginner · Selecting and filtering data

Filter data with pandas query(), with examples

The pandas query() method explained: filter rows with readable string conditions, use variables with @, in and not in, and column names with spaces.

By theprogrammers team · · 5 min read

Filtering in pandas with square brackets works, but long conditions get hard to read: orders[(orders["city"] == "Delhi") & (orders["amount"] > 2000)] repeats orders three times. The query() method lets you write the same filter as a short string that reads almost like English: orders.query("city == 'Delhi' and amount > 2000").

This lesson shows how to write conditions with query(), use Python variables inside them, handle awkward column names, and decide when query() is the better choice. It builds on filter rows in pandas, so read that first if filtering is new to you.

We'll use the same orders data:

import pandas as pd

orders = pd.DataFrame({
    "order_id": [101, 102, 103, 104, 105, 106, 107],
    "city":     ["Kanpur", "Delhi", "Kanpur", "Pune", "Delhi", "Lucknow", "Pune"],
    "category": ["Books", "Mobiles", "Fashion", "Books", "Fashion", "Mobiles", "Books"],
    "amount":   [450, 15999, 1200, 300, 2500, 9999, None],
    "paid":     [True, True, False, True, True, False, True],
})

Your first query

Write the condition as a string, using column names directly:

print(orders.query("amount > 1000"))
   order_id     city category   amount   paid
1       102    Delhi  Mobiles  15999.0   True
2       103   Kanpur  Fashion   1200.0  False
4       105    Delhi  Fashion   2500.0   True
5       106  Lucknow  Mobiles   9999.0  False

That's exactly the same result as orders[orders["amount"] > 1000]. Text values go in quotes inside the string: use single quotes inside double quotes, or the other way round:

print(orders.query("city == 'Pune'"))

Combining conditions

Inside query() you can write plain and, or and not, and you don't need brackets around each comparison:

print(orders.query("city == 'Delhi' and amount > 2000"))
   order_id   city category   amount  paid
1       102  Delhi  Mobiles  15999.0  True
4       105  Delhi  Fashion   2500.0  True
print(orders.query("category == 'Books' or not paid"))

&, | and ~ work too. Use brackets when you mix and and or, to make the order obvious: "(city == 'Delhi' or city == 'Pune') and paid".

Ranges, written naturally

Chained comparisons work the way you'd write them in maths:

print(orders.query("1000 <= amount <= 10000"))
   order_id     city category  amount   paid
2       103   Kanpur  Fashion  1200.0  False
4       105    Delhi  Fashion  2500.0   True
5       106  Lucknow  Mobiles  9999.0  False

Lists of values: in and not in

print(orders.query("city in ['Kanpur', 'Lucknow']"))
print(orders.query("category not in ['Mobiles', 'Fashion']"))

These are the query() versions of isin and ~isin.

Using Python variables with @

Real code rarely hard-codes values. Put @ before a variable name to use it inside the query:

min_amount = 2000
cities = ["Delhi", "Pune"]

print(orders.query("amount >= @min_amount and city in @cities"))
   order_id   city category   amount  paid
1       102  Delhi  Mobiles  15999.0  True
4       105  Delhi  Fashion   2500.0  True

Without the @, pandas looks for a column called min_amount and raises UndefinedVariableError.

An f-string also works, orders.query(f"amount >= {min_amount}"), but @ is safer: you don't have to worry about quoting text values, and it works for lists.

Column names with spaces

If a column name has spaces or symbols, wrap it in backticks:

sales = pd.DataFrame({"unit price": [100, 250], "qty": [3, 1]})
print(sales.query("`unit price` > 150"))
   unit price  qty
1         250    1

The backtick key is usually to the left of 1 on your keyboard.

Text methods and missing values

You can call .str methods inside a query:

print(orders.query("city.str.startswith('L')"))

For missing values, use isna() and notna():

print(orders.query("amount.isna()"))
   order_id  city category  amount  paid
6       107  Pune    Books     NaN  True

Calculations inside a query

You can compare columns with each other, or with calculations:

marks = pd.DataFrame({"name": ["Ahana", "Rohan", "Meera"],
                      "maths": [88, 64, 91], "physics": [72, 70, 95]})
print(marks.query("maths > physics + 10"))
    name  maths  physics
0  Ahana     88       72

Chaining query with other methods

query() returns a DataFrame, so it fits naturally in a chain of steps. Wrapping the chain in brackets lets you put one step per line:

result = (
    orders
    .query("paid and amount > 400")
    .sort_values("amount", ascending=False)
    [["order_id", "city", "amount"]]
)
print(result)
   order_id    city   amount
1       102   Delhi  15999.0
4       105   Delhi   2500.0
0       101  Kanpur    450.0

Read it top to bottom: take the orders, keep the paid ones above ₹400, sort by amount, pick three columns.

query() or square brackets?

df.query("...")df[...]
ReadabilityShort, reads like EnglishRepeats the DataFrame name
VariablesNeed @Used directly
Mistakes in namesFound only when the line runsFound only when the line runs
Editor helpNo autocomplete inside the stringAutocomplete works
Works on any conditionMost conditionsAll conditions

Both give the same result, and both are fast. Use query() when it makes a filter easier to read, especially with several conditions, and brackets when the condition is complex Python logic. Many teams pick one style and stick to it.

Practice

  1. Find Books orders under ₹500 using query().
Show the answer
print(orders.query("category == 'Books' and amount < 500"))

Orders 101 and 104.

  1. Store a list of categories in a variable and find paid orders in those categories.
Show the answer
wanted = ["Books", "Mobiles"]
print(orders.query("category in @wanted and paid"))
  1. In the marks table, find students whose average of maths and physics is above 80.
Show the answer
print(marks.query("(maths + physics) / 2 > 80"))

Meera, with an average of 93.

Interview questions

What does pandas query() do?

It filters rows using a boolean expression written as a string, where column names are used directly. It returns a new DataFrame, the same as boolean indexing.

How do you use a Python variable inside query()?

Prefix it with @, for example df.query("price > @limit"). Without @, pandas treats the name as a column.

How do you reference a column with a space in its name in query()?

Wrap it in backticks: `df.query("unit price > 100")`.

What to learn next

  1. Put your filtered rows in order with sort and rank data in pandas.
  2. Revisit choosing rows and columns in loc vs iloc in pandas.