Sub topic 7
Combining conditions
This chapter assumes you can build a single boolean mask such as df["population_k"] > 3000 and use it to filter rows. Here you will combine several masks into one filter. You will also see why Python's and, or, and not don't work on masks and what goes wrong when parentheses are missing.
Setup
The examples reuse the city table from earlier chapters.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"country": ["Norway", "Peru", "India", "Egypt", "Ecuador"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)Masks are combined element by element
A comparison on a column returns a boolean Series with one True or False per row. To require two conditions, combine the two Series position by position, matching rows by index label. Pandas overloads three operators for this.
| Operator | Meaning | Python word it replaces | Column |
|---|---|---|---|
| `&` | True where both masks are True | `and` | |
| `\ | ` | True where at least one mask is True | `or` |
| `~` | Flips every value | `not` | |
| `^` | True where exactly one mask is True | none |
big = df["population_k"] > 3000
south_america = df["continent"] == "South America"
print(df[big & south_america]) # Lima only
print(df[big | south_america]) # Lima, Pune, Cairo, Quito
print(df[~big]) # Oslo, Quito
print(df[big ^ south_america]) # Pune, Cairo, QuitoThe last line keeps rows that match one condition but not both. Lima is large and in South America, so ^ drops it.
Why `and`, `or`, and `not` fail
Python's and needs a single truth value on each side. A Series with five values has no single truth value, so pandas raises a ValueError saying the truth value of a Series is ambiguous.
try:
df[(df["population_k"] > 3000) and (df["continent"] == "South America")]
except ValueError as error:
print("ValueError:", error)and, or, and not cannot be overloaded to work element by element. The bitwise operators can, so pandas uses them.
Parentheses are required around comparisons
In Python, & and | bind more tightly than comparison operators such as > and ==. Without parentheses, the expression is grouped differently from what you read.
# Wrong: Python evaluates 3000 & df["continent"] first
# df[df["population_k"] > 3000 & df["continent"] == "South America"]That line is commented out because it fails. It is read as df["population_k"] > (3000 & df["continent"]) == "South America". It raises a TypeError, because an integer and a column of strings cannot be combined with &. Two fixes work:
# Fix 1: parentheses around each comparison
mask = (df["population_k"] > 3000) & (df["continent"] == "South America")
print(df[mask])
# Fix 2: name each condition first, as in the earlier example
big = df["population_k"] > 3000
south_america = df["continent"] == "South America"
print(df[big & south_america])Naming conditions also makes long filters easier to read and test one piece at a time.
Operator precedence
When you mix operators, use this order, from tightest to loosest binding:
~&^|- Comparisons (
>,==,<=, and so on)
Two consequences follow.
~big & south_americameans(~big) & south_america. It keeps rows that are not big and are in South America. That is Quito.a | b & cmeansa | (b & c). Add parentheses when you mix&and|, even when the default grouping is what you want. A reader should not have to remember the table.
europe = df["continent"] == "Europe"
# Large cities, or small cities in Europe or South America
mask = big | (~big & (europe | south_america))
print(df[mask])
# Not (big and in South America): everything except Lima
print(df[~(big & south_america)])The second filter shows that ~ applies to the whole parenthesized expression. By De Morgan's laws, ~(big & south_america) is the same as ~big | ~south_america.
Combining many conditions
For two or three conditions, chaining operators is fine. When the conditions come from a list, such as user-supplied filters, fold them together with functools.reduce.
import operator
from functools import reduce
conditions = [
df["population_k"] > 3000,
df["continent"] != "Asia",
df["country"].str.len() > 4,
]
all_of = reduce(operator.and_, conditions)
any_of = reduce(operator.or_, conditions)
print(df[all_of]) # Cairo only
print(df[any_of]) # every row matches at least one conditionUse operator.and_ and operator.or_, not and and or. They are the function forms of & and |. Keep the list non-empty, because reduce without a starting value raises an error on an empty list.
Masks align on the index
When you combine two Series with &, pandas matches them by index label, not by position. If both masks come from the same DataFrame, the labels already match. Masks built from a different object can misalign.
other = pd.Series([True, False, True], index=["a", "b", "z"])
# Pandas cannot align these cleanly. The labels differ, so the result
# is a mask with extra labels, and filtering df with it raises an error.
combined = (df["population_k"] > 3000) & other
print(combined)The printed result has labels a, b, c, d, e, and z, and rows without a partner count as False. A mask with labels that don't all exist in df cannot be used to filter df and raises an error. If you must combine masks from different sources, convert one to a plain array with .to_numpy() so that matching is by position, and check that the lengths agree first.
Negation and missing values
Comparisons involving NaN evaluate to False. This creates a trap with ~, because it flips those False values to True.
scores = pd.DataFrame({"name": ["x", "y", "z"], "score": [1.0, None, 3.0]})
print(scores[scores["score"] > 2]) # z
print(scores[~(scores["score"] > 2)]) # x and y: the missing score is kept
print(scores[scores["score"] <= 2]) # x only: the missing score is dropped~(score > 2) and score <= 2 look equivalent, but they differ on the missing row. Decide what you want for missing values and say so in the filter.
has_score = scores["score"].notna()
print(scores[has_score & (scores["score"] <= 2)])Using combined masks with .loc
A combined mask works the same way inside .loc. This is the form to use when you also want to choose columns or assign values.
mask = (df["population_k"] > 3000) | (df["continent"] == "Europe")
print(df.loc[mask, ["city", "population_k"]])The mask picks the rows, and the list picks the columns, in a single call.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `ValueError` about an ambiguous truth value | Used `and`, `or`, or `not` on Series | Use `&`, `\ | `, `~` |
| `TypeError` mentioning `&` or a dtype | Missing parentheses around comparisons | Parenthesize each comparison or name each mask | |
| Filter keeps rows with missing values unexpectedly | `~` flipped the `False` that `NaN` comparisons produce | Add `.notna()` or use the opposite comparison | |
| Error or odd result when combining masks | Masks have different index labels | Build all masks from the same DataFrame, or use `.to_numpy()` |
Exercise
Using the city DataFrame above, write one expression that selects cities that are not in Asia and have a population above 2,500 thousand but at most 10,100 thousand. Which city labels does it return?
Show answer
Use parentheses around each comparison: df[(df["continent"] != "Asia") & (df["populationk"] > 2500) & (df["populationk"] <= 10100)]. It returns rows b (Lima, 10092) and e (Quito, 2800). Oslo (709) fails the lower bound, Pune is in Asia, and Cairo (10230) exceeds the upper bound.
Exercise
Given scores with a score column of [1.0, NaN, 3.0], why does scores[~(scores["score"] > 2)] return two rows, and how would you return only rows whose score is present and at most 2?
Show answer
The comparison NaN > 2 is False, so ~ turns it into True and the row with the missing score is kept along with the row scoring 1.0. To keep only present scores of at most 2, use scores[scores["score"].notna() & (scores["score"] <= 2)].