BitBootcampBitBootcamp ← all explainers 🔄 Review ⚙ Settings

PD-01-007-P · Primer — Boolean Filtering

The idea in one sentence

To keep only the rows you care about, you first write a condition that produces a column of True/False values — one per row — and then hand that column of answers back to the DataFrame, which returns exactly the rows marked True.

Why it exists

Real data always arrives with more than you want. You have a table of every customer, but you only want the ones over 30; a log of every event, but only the errors; a spreadsheet of every sale, but only the ones in New York. In a spreadsheet you'd reach for a filter dropdown; in pandas you need a way to say "give me the subset of rows where this is true" that works on ten rows or ten million, the same way every time.

pandas answers this with a two-step idea called boolean filtering (also known as boolean indexing). Instead of looping over rows and checking each one yourself — slow to write and slow to run — you describe the condition once, applied to the whole column at once, and pandas evaluates it for every row in a single vectorized sweep. The result of that condition is a boolean mask: a Series of True/False the same length as your data. Feeding that mask back to the DataFrame is the actual filter. Once this two-step rhythm clicks — build the mask, apply the mask — nearly every "just the rows where..." task in your career becomes the same short, readable move.

How it works

A comparison operator like >=, ==, !=, <, or > applied to a column runs element-by-element and returns a boolean mask — a True/False Series with one entry per row. You apply that mask with df[mask], and pandas keeps only the rows where the mask is True, carrying their original index labels along. To combine conditions you use & for "and" and | for "or" — each side must be wrapped in ( ) because of Python's operator precedence — and ~ to negate. Note that these are the bitwise symbols, not the words and/or, which don't work here. The mask is just data, so you can build it, print it, and reuse it. Here is the whole idea end to end:

import pandas as pd

df = pd.DataFrame({
    "name": ["Ana", "Ben", "Cleo", "Dara", "Eli"],
    "city": ["NYC", "LA",  "NYC",  "LA",   "NYC"],
    "age":  [34,    28,    41,     19,     52],
})

mask = df["age"] >= 30          # a boolean Series: [True, False, True, False, True]
print(df[mask])                 # keep rows where mask is True
#    name city  age
# 0   Ana  NYC   34
# 2  Cleo  NYC   41
# 4   Eli  NYC   52

# Combine conditions: age >= 30 AND city == "NYC"  (note the parentheses)
print(df[(df["age"] >= 30) & (df["city"] == "NYC")])
#    name city  age
# 0   Ana  NYC   34
# 2  Cleo  NYC   41
# 4   Eli  NYC   52

Notice the surviving rows keep their original index labels (0, 2, 4) — filtering removes rows, it doesn't renumber the ones that stay.

The one gotcha

When you combine two conditions you must use &/|, wrap each condition in parentheses, and never use Python's and/or. This trips up almost everyone at first because it looks like plain Python. Write df["age"] >= 30 and df["city"] == "NYC" and you get a loud ValueError: The truth value of a Series is ambiguous — because and tries to collapse a whole column of True/False into a single yes/no, and pandas refuses to guess. The fix is &, which combines the two masks element-by-element. But & binds tighter than >= in Python, so if you drop the parentheses — df["age"] >= 30 & df["city"] == "NYC" — Python secretly evaluates 30 & df["city"] first and everything falls apart. The rule that keeps you safe every time: one condition per pair of parentheses, joined by & or |. So (df["age"] >= 30) & (df["city"] == "NYC"), (a) | (b), and ~(a) for "not."

See it — condition becomes a mask, mask selects the rows

flowchart LR
    A["DataFrame<br/>5 rows<br/>name, city, age"] --> B["age >= 30<br/>(comparison<br/>per row)"]
    B --> C["boolean mask<br/>T,F,T,F,T<br/>(one per row)"]
    C --> D["df[mask]<br/>keep the True rows"]
    D --> E["result<br/>3 rows<br/>(index 0, 2, 4)"]

The one-line takeaway

Filtering is two steps — build a boolean mask with a comparison, then apply it with df[mask] — and when you combine conditions, use &/| with each side in its own parentheses, never and/or.

Where you'll meet it

You'll meet boolean filtering on essentially your first real day with pandas, and then every day after: "show me the orders above $100," "drop the rows with a null email," "keep only last month's signups," "flag the users in Europe." It is the entry point to almost every analysis, because you almost never want the whole table — you want a slice of it, and this is how you carve the slice. It pairs naturally with the next steps you'll learn: filter first, then groupby to summarize, or filter then compute a mean. In interviews and take-homes it shows up constantly, often as a two-condition trap ("customers in NYC who are over 30") where the interviewer is quietly checking whether you reach for & with parentheses or fumble into and and the ambiguous-truth-value error. Master the build-a-mask, apply-a-mask rhythm and you've got a tool you'll use in nearly every pandas script you ever write.

Named concepts: boolean mask, comparison operators, row filtering, combining conditions