Skip to content

Filtering with Conditions (and, or, isin, query)

A boolean filter works in two steps: first you build a mask — a Series of True/False, one per row — then you use that mask to keep only the True rows.

Setup DataFrame
import pandas as pd
 
df = pd.DataFrame({
    "name": ["Asha", "Ravi", "Meera", "Zoya", "Kabir"],
    "age": [23, 28, 26, 31, 22],
    "city": ["Pune", "Delhi", "Delhi", "Pune", "Mumbai"],
    "score": [88, 91, 77, 95, 60],
})
 
print(df)
Single condition
print(df[df["age"] >= 25])

Pandas uses bitwise operators:

  • AND: &
  • OR: |

Always use parentheses:

AND filter
mask = (df["city"] == "Delhi") & (df["score"] >= 80)
print(df[mask])
OR filter
mask = (df["city"] == "Mumbai") | (df["score"] >= 90)
print(df[mask])
isin
mask = df["city"].isin(["Pune", "Delhi"])
print(df[mask])
between
mask = df["age"].between(23, 30, inclusive="both")
print(df[mask])

query() can be easier to read, especially in notebooks.

query
result = df.query('city == "Delhi" and score >= 80')
print(result)
query with variable
min_score = 85
result = df.query('score >= @min_score')
print(result)
  • Using and / or instead of & / | (will error)
  • Forgetting parentheses around conditions
  • Comparing strings with extra spaces (clean using .str.strip())
diagram Boolean mask filtering mermaid
A condition produces a True/False mask; indexing with that mask keeps only the True rows.
sketch A condition becomes a keep/drop mask p5.js
Each row is tested against the condition; only rows where the mask is True survive the filter.

Once you can pull out the rows you want, the next skill is reordering them — continue to Sorting and Ranking.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading