← Back to Pandas Course | Chapter 4: Indexing & Selection | Lesson 5 of 7

query()

query lets you filter rows by writing the condition as a readable string.

In this page:

  1. query()
Syntax
python
df.query("column > value and other_column == 'text'")

query()

df.query("age > 30 and city == Oslo") reads like plain English and allows and, or and not. Reference Python variables with an @ prefix. It can be more compact than boolean masks, especially for long conditions.

Note: For column names with spaces, wrap them in backticks.

Example: query()

python
import pandas as pd

df = pd.DataFrame({"name": ["Ann", "Bob", "Cy"], "age": [28, 35, 41], "city": ["Oslo", "Rome", "Oslo"]})
limit = 30
print(df.query("age > @limit and city == 'Oslo'"))
print(df.query("name in ['Ann', 'Bob']"))

# Output:
#   name  age  city
# 2   Cy   41  Oslo
#   name  age  city
# 0  Ann   28  Oslo
# 1  Bob   35  Rome
Related Topics
Common Mistakes
  1. Forgetting quotes around string values
  2. Not using @ for outside variables
  3. Long complex logic that is clearer as masks
Chapter Summary
  • query takes a condition string
  • Use and, or, not
  • @var references variables
  • Backticks quote odd column names
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.