Boolean indexing
Put a condition inside brackets to keep only the rows that satisfy it.
In this page:
Syntax
df[df["column"] > value]
df[(df["column1"] > a) & (df["column2"] == b)]
Boolean indexing
A condition such as df["age"] > 30 produces a boolean Series. df[condition] keeps rows where it is True. Combine conditions with &, | and ~, each wrapped in parentheses, and use isin, between and str.contains for common tests.
Note:
df[~mask] keeps the rows that do NOT match.
Example: Boolean indexing
import pandas as pd
df = pd.DataFrame({"name": ["Ann", "Bob", "Cy"], "age": [28, 35, 41], "city": ["Oslo", "Rome", "Oslo"]})
print(df[df["age"] > 30])
print(df[(df["city"] == "Oslo") & (df["age"] > 30)])
print(df[df["name"].isin(["Ann", "Cy"])])
# Output:
# name age city
# 1 Bob 35 Rome
# 2 Cy 41 Oslo
# name age city
# 2 Cy 41 Oslo
# name age city
# 0 Ann 28 Oslo
# 2 Cy 41 Oslo
Related Topics
Common Mistakes
- Using and / or between conditions
- Forgetting parentheses
- Filtering then assigning on a copy
Chapter Summary
- A condition yields a boolean Series
- Brackets filter rows
- Combine with & | ~
- isin and between simplify tests
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: