Sub topic 4
Boolean masks instead of if statements
This chapter replaces if/else logic inside row loops with boolean masks. A mask is a column of True and False values that you compute once for the whole DataFrame.
Prerequisites
You should be comfortable with these:
- Creating a DataFrame and selecting columns with
df["col"]. - Column arithmetic, such as
df["price"] * df["qty"], from the previous chapters. - Python's
and,orandnotoperators.
The loop you are replacing
A common first attempt at conditional logic visits each row and tests it with if:
import numpy as np
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3, 4, 5],
"price": [10.0, 20.0, 15.0, 8.0, np.nan],
"qty": [3, 1, 4, 10, 2],
"region": ["north", "south", "north", "east", "south"],
})
flags = []
for _, row in df.iterrows():
if row["qty"] >= 3 and row["price"] > 9:
flags.append(True)
else:
flags.append(False)
print(flags)This prints [True, False, True, False, False]. It works, but it builds a Series for every row and runs the Python interpreter once per row. The mask version below does the same job with whole-column operations.
What a mask is
Comparing a column with a value gives a new Series of booleans with the same index as the original:
mask = (df["qty"] >= 3) & (df["price"] > 9)
print(mask.tolist())The output is [True, False, True, False, False], the same as the loop. The comparison runs inside compiled NumPy code, so there is no per-row Python work.
The mask is an ordinary value. You can store it in a variable, name it, combine it with other masks and reuse it. Naming masks after the business rule they express (is_bulk, has_price) makes the code read like the rule.
Translating Python operators
Python's and, or and not ask for one truth value from an object. A Series holds many values, so pandas cannot answer, and it raises an error. Use the element-wise operators instead.
| Scalar Python | Mask version | Notes | Column |
|---|---|---|---|
| `a and b` | `mask_a & mask_b` | Both conditions must hold in the same row | |
| `a or b` | `mask_a \ | mask_b` | At least one condition holds |
| `not a` | `~mask_a` | Flips every value | |
| `x in (1, 2)` | `s.isin([1, 2])` | Membership test for the whole column | |
| `lo <= x <= hi` | `s.between(lo, hi)` | Both ends included by default | |
| `x is None` | `s.isna()` | Also catches `NaN` and `NaT` |
Parentheses are required
The & and | operators bind more tightly than comparison operators such as >=. Without parentheses, Python reads df["qty"] >= 3 & df["price"] > 9 as a chained comparison around 3 & df["price"], which fails. Put every comparison in its own parentheses:
ok = (df["qty"] >= 3) & (df["price"] > 9)
either = (df["qty"] >= 10) | (df["region"] == "south")
not_north = ~(df["region"] == "north")The last line is clearer as df["region"] != "north". Reserve ~ for cases such as negating isin, isna or str.contains.
The ambiguity error
If you write and by mistake, pandas stops with a ValueError:
try:
bad = (df["qty"] >= 3) and (df["price"] > 9)
except ValueError as err:
print(err)The message begins "The truth value of a Series is ambiguous". When you see it, look for and, or, not, if series: or a chained comparison like 3 <= df["qty"] <= 5. Replace each one with &, |, ~ or between.
Using a mask
A mask can be used in three ways.
Filtering
Putting a mask inside square brackets keeps the rows where it is True:
big_orders = df[df["qty"] >= 3]
print(big_orders["order_id"].tolist())This prints [1, 3, 4]. The result is a new DataFrame, and the original is unchanged.
Assigning to selected rows
To change values only where a condition holds, use .loc[mask, column]. This is the direct replacement for if cond: row[col] = value:
df["discount"] = 0.0
df.loc[ok, "discount"] = 0.10
print(df["discount"].tolist())The output is [0.1, 0.0, 0.1, 0.0, 0.0]. The first line creates the default for all rows, and the second overrides it where the mask is True. This default-then-override pattern replaces the else branch.
Counting and summarising
True counts as 1 and False as 0 in arithmetic. That makes counting and proportions short:
print(ok.sum())
print(ok.mean())
print(ok.any(), ok.all())This prints 2, 0.4, then True False. A loop that increments a counter inside an if becomes mask.sum().
Mask helpers for common tests
Several methods build masks for tests that would otherwise need a loop:
in_region = df["region"].isin(["north", "east"])
mid_qty = df["qty"].between(2, 5)
missing_price = df["price"].isna()
mentions_nor = df["region"].str.contains("nor", na=False)isintakes any list-like. For a large lookup list, pass a set or an array, which is faster than a long chain of|comparisons.between(lo, hi)includes both ends. Passinclusive="left","right"or"neither"to change that.str.containstreats its pattern as a regular expression by default. Passregex=Falsefor literal text such as"a.b".na=Falseinstr.containsmakes missing text count as "no match". Without it, the result containsNaNand cannot be used directly as a mask.
Edge cases
Missing values fail every comparison
Row 5 has price = NaN. Any comparison with NaN is False, including !=:
print((df["price"] > 9).tolist())
print((df["price"] <= 9).tolist())
print((~(df["price"] > 9)).tolist())The first line gives [True, True, True, False, False]. The second gives [False, False, False, True, False]. The third gives [False, False, False, True, True]. Row 5 is in neither > 9 nor <= 9, but it is in ~(df["price"] > 9). If your rule is "not expensive", decide explicitly whether missing prices belong in it. Test for missing data separately with isna() and combine the masks:
cheap_or_missing = (df["price"] <= 9) | df["price"].isna()Chained assignment does not write back
The pattern df[mask]["discount"] = 0.1 first creates a filtered copy, then assigns into that copy. The original DataFrame is not changed. Older pandas versions emit SettingWithCopyWarning. With Copy-on-Write, which is the default in pandas 3, the assignment silently has no effect on df. Always use a single .loc[mask, "discount"] = 0.1.
Masks align on the index
When you filter with a boolean Series, pandas matches it to the DataFrame by index label, not by position. A mask built from the same DataFrame always lines up. A mask built from a different DataFrame, or from a filtered subset, may not:
subset = df[df["qty"] >= 3]
other_mask = subset["price"] > 12
try:
df[other_mask]
except Exception as err:
print(type(err).__name__)The mask has only three index labels (0, 2, 3), and df has five rows. This raises IndexingError ("Unalignable boolean Series provided as indexer"). Build masks from the frame you are indexing, or use other_mask.reindex(df.index, fill_value=False) when the mismatch is intended.
A plain NumPy array of booleans skips alignment, so its length must equal the number of rows. A wrong length raises an IndexError.
Nullable booleans
Columns with the boolean extension dtype can hold pd.NA. When such a mask is used in .loc or [], pandas treats NA as False. Reductions such as any() skip NA by default, so check the dtype if counts look wrong.
Reuse masks, and watch the cost of copies
Each df[mask] copies the selected rows. If you only need one column from the selected rows, select it directly with df.loc[mask, "price"]. If you need the same mask several times, compute it once and keep it in a variable.
When a mask is not enough
A mask handles one if with a single outcome. When a row must receive one of two values, or one of several values, assigning with .loc repeatedly becomes clumsy and its order matters. The next chapter introduces numpy.where and numpy.select, which build such columns in one expression using the masks you learned here.
Exercise
Using the DataFrame df from this chapter, write a mask expression for "orders from the north or south region with a quantity from 2 to 4 inclusive". Then write one line that sets a new column flag to True for those rows and False for all others. Which rows (by order_id) are flagged?
Show answer
mask = df["region"].isin(["north", "south"]) & df["qty"].between(2, 4) df["flag"] = mask The mask is True for order 1 (north, qty 3), order 3 (north, qty 4) and order 5 (south, qty 2). Order 2 has qty 1 and order 4 is in the east region with qty 10, so neither matches. The flagged order_ids are 1, 3 and 5. Assigning the mask directly works because it is already a boolean Series with the same index as df.
Exercise
A colleague writes df[(df["price"] > 9) | (df["price"] <= 9)] expecting to get every row back. How many rows come back for the example df, and why?
Show answer
Four rows come back (order_ids 1 to 4). Order 5 has price NaN, and both NaN > 9 and NaN <= 9 are False, so no row with a missing price passes either test. To keep every row, add | df["price"].isna() or skip the filter.