query()
query lets you filter rows by writing the condition as a readable string.
In this page:
Syntax
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()
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
- Forgetting quotes around string values
- Not using @ for outside variables
- 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: