Sub topic 4
Boolean masks instead of if statements
This chapter assumes you can create a DataFrame, select columns, and write basic Python loops and conditionals. It also assumes you know that df["price"] * df["qty"] works on whole columns, which the previous chapter covered.
The loop you want to replace
A common row loop checks a condition and then acts on the row. Here is one that flags large orders:
import pandas as pd
df = pd.DataFrame({
"price": [10.0, 20.0, 15.0, 5.0],
"qty": [3, 1, 4, 10],
})
flags = []
for _, row in df.iterrows():
if row["qty"] >= 3:
flags.append(True)
else:
flags.append(False)
df["large_loop"] = flagsThe loop builds a Series for every row and runs a Python if each time. A boolean mask does the same work in one operation.
What a boolean mask is
A boolean mask is a Series of True and False values with the same index as the DataFrame. Comparing a column to a value produces one:
mask = df["qty"] >= 3
print(mask)0 True
1 False
2 True
3 True
Name: qty, dtype: boolThe comparison runs over the whole column at once, in the same way as column arithmetic. The mask can be stored as a column, used to select rows, or used to update rows.
df["large"] = df["qty"] >= 3
big_orders = df[df["qty"] >= 3]Combining conditions
Python's and, or and not do not work on Series. They try to turn a whole Series into a single True or False, and pandas raises a ValueError. Use the element-wise operators instead:
| Python logic | Mask operator | Column |
|---|---|---|
| `and` | `&` | |
| `or` | `\ | ` |
| `not` | `~` |
Wrap each comparison in parentheses. The & and | operators bind more tightly than comparisons, so without parentheses the expression is evaluated in the wrong order.
cheap_and_large = (df["price"] < 12) & (df["qty"] >= 3)
cheap_or_large = (df["price"] < 12) | (df["qty"] >= 3)
not_large = ~(df["qty"] >= 3)
print(df[cheap_and_large])Updating rows with .loc
A mask can also choose which rows to change. Use .loc[mask, column] for the assignment:
df["discount"] = 0.0
df.loc[df["qty"] >= 3, "discount"] = 0.05
df.loc[df["qty"] >= 10, "discount"] = 0.10The second line sets only the rows where the mask is True. Other rows keep their earlier value. Later assignments overwrite earlier ones, so order them from the broadest condition to the narrowest.
Avoid chained indexing such as df[df["qty"] >= 3]["discount"] = 0.05. It can modify a temporary copy and leave df unchanged.
Counting and testing with masks
True counts as 1 and False as 0, so aggregations on a mask answer common questions without a loop:
mask = df["qty"] >= 3
print(mask.sum()) # how many rows match
print(mask.mean()) # fraction of rows that match
print(mask.any()) # does at least one row match
print(mask.all()) # do all rows matchFor membership tests, use isin in place of a chain of or conditions:
df[df["qty"].isin([1, 4])]Two other helpers are between for ranges and isna for missing values:
df[df["price"].between(10, 20)]
df[df["price"].notna()]Common errors
ValueError: The truth value of a Series is ambiguous. You usedand,or,not, or anifon a Series. Switch to&,|,~.- Misaligned results. A mask built from a different DataFrame is matched on index labels, not position. Index alignment is covered in a later chapter.
SettingWithCopyWarning. You assigned through chained indexing. Use.loc[mask, column].
Exercise
Given the DataFrame above, write one line that selects the rows where price is at least 10 and qty is not 1, and one .loc line that sets a new column flag to "review" for those rows (assume flag already exists as a column of empty strings).
Show answer
subset = df[(df["price"] >= 10) & (df["qty"] != 1)] selects the rows. df.loc[(df["price"] >= 10) & (df["qty"] != 1), "flag"] = "review" updates them. Each comparison is in parentheses and the two are joined with &, not and.