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

Boolean indexing

Put a condition inside brackets to keep only the rows that satisfy it.

In this page:

  1. Boolean indexing
Syntax
python
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

python
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
  1. Using and / or between conditions
  2. Forgetting parentheses
  3. 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:

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.