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.
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
Section titled “Basic boolean filtering”print(df[df["age"] >= 25])Multiple conditions: AND / OR
Section titled “Multiple conditions: AND / OR”Pandas uses bitwise operators:
- AND:
& - OR:
|
Always use parentheses:
mask = (df["city"] == "Delhi") & (df["score"] >= 80)
print(df[mask])mask = (df["city"] == "Mumbai") | (df["score"] >= 90)
print(df[mask])isin() for membership checks
Section titled “isin() for membership checks”mask = df["city"].isin(["Pune", "Delhi"])
print(df[mask])between() for range filters
Section titled “between() for range filters”mask = df["age"].between(23, 30, inclusive="both")
print(df[mask])query() for readable filters
Section titled “query() for readable filters”query() can be easier to read, especially in notebooks.
result = df.query('city == "Delhi" and score >= 80')
print(result)Variables inside query
Section titled “Variables inside query”min_score = 85
result = df.query('score >= @min_score')
print(result)Common mistakes
Section titled “Common mistakes”- Using
and/orinstead of&/|(will error) - Forgetting parentheses around conditions
- Comparing strings with extra spaces (clean using
.str.strip())
Visualize it
Section titled “Visualize it”flowchart LR A["df['score'] >= 80"] --> B["Boolean mask (True/False per row)"] B --> C["df[mask]"] C --> D["Only matching rows"]
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Build a Boolean Mask
Section titled “Exercise 1 – Build a Boolean Mask”Exercise 2 – Combine Conditions With &
Section titled “Exercise 2 – Combine Conditions With &”Exercise 3 – Membership With isin
Section titled “Exercise 3 – Membership With isin”Once you can pull out the rows you want, the next skill is reordering them — continue to Sorting and Ranking.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading