Skip to content

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

Setup

A boolean filter works in two steps: first you build a mask — a Series of TrueTrue/FalseFalse, one per row — then you use that mask to keep only the TrueTrue 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)
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)

Basic boolean filtering

Single condition
print(df[df["age"] >= 25])
Single condition
print(df[df["age"] >= 25])

Multiple conditions: AND / OR

Pandas uses bitwise operators:

  • AND: &&
  • OR: ||

Always use parentheses:

AND filter
mask = (df["city"] == "Delhi") & (df["score"] >= 80)
print(df[mask])
AND filter
mask = (df["city"] == "Delhi") & (df["score"] >= 80)
print(df[mask])
OR filter
mask = (df["city"] == "Mumbai") | (df["score"] >= 90)
print(df[mask])
OR filter
mask = (df["city"] == "Mumbai") | (df["score"] >= 90)
print(df[mask])

isin()isin() for membership checks

isin
mask = df["city"].isin(["Pune", "Delhi"])
print(df[mask])
isin
mask = df["city"].isin(["Pune", "Delhi"])
print(df[mask])

between()between() for range filters

between
mask = df["age"].between(23, 30, inclusive="both")
print(df[mask])
between
mask = df["age"].between(23, 30, inclusive="both")
print(df[mask])

query()query() for readable filters

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

query
result = df.query('city == "Delhi" and score >= 80')
print(result)
query
result = df.query('city == "Delhi" and score >= 80')
print(result)

Variables inside query

query with variable
min_score = 85
result = df.query('score >= @min_score')
print(result)
query with variable
min_score = 85
result = df.query('score >= @min_score')
print(result)

Common mistakes

  • Using andand / oror instead of && / || (will error)
  • Forgetting parentheses around conditions
  • Comparing strings with extra spaces (clean using .str.strip().str.strip())

Visualize it

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.

🧪 Try It Yourself

Exercise 1 – Build a Boolean Mask

Exercise 2 – Combine Conditions With &

Exercise 3 – Membership With isin

Next

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

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did