Sub topic 7
Combining Conditions
This chapter assumes you can build a boolean mask from a single comparison and use it to filter rows. It also assumes you have the df DataFrame of five cities from the earlier chapters. Here you combine several conditions into one filter.
Why Python's `and` and `or` do not work
A boolean mask is a Series of True and False values, one per row. To combine two masks you need an operation that works element by element. Python's and, or, and not ask for a single truth value for a whole object. On a Series that raises a ValueError. Use the operators below instead.
| Operator | Meaning | Python keyword it replaces | Column |
|---|---|---|---|
| `&` | both conditions are true | `and` | |
| `\ | ` | at least one condition is true | `or` |
| `~` | the condition is not true | `not` |
Combining two masks
Store each comparison in its own variable. Then combine the variables.
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"],
)
big = df["population_k"] > 3000
south_america = df["continent"] == "South America"
print(df[big & south_america]) # big AND in South America
print(df[big | south_america]) # big OR in South America
print(df[~big]) # NOT bigThe first filter keeps only Lima. The second keeps Lima, Pune, Cairo, and Quito. The third keeps Oslo and Quito, the cities with 3000 thousand people or fewer.
Parentheses when you write conditions inline
The operators &, |, and ~ bind more tightly than comparisons such as > and ==. Without parentheses, pandas reads df["population_k"] > 3000 & df["continent"] == "South America" in the wrong order and raises an error. If you write the comparisons inline, wrap each one.
result = df[(df["population_k"] > 3000) & (df["continent"] == "South America")]
print(result)Named variables avoid this problem and make longer filters easier to read.
Building up a longer filter
You can chain more than two masks. Use parentheses to make the grouping clear when you mix & and |, because & is evaluated before |.
europe_or_asia = (df["continent"] == "Europe") | (df["continent"] == "Asia")
mid_size = df["population_k"].between(700, 5000)
print(df[europe_or_asia & mid_size])Oslo (709) and Pune (3124) both pass. The ~ operator can also wrap a combined mask. df[~(big & south_america)] keeps every row except Lima.
The diagram shows how the masks flow into one filter.
Common errors
- Using
and,or, ornoton Series. This raises aValueError. - Leaving out parentheses around inline comparisons. This raises a
ValueErroror aTypeError. - Using
~on a column of integers instead of booleans. It flips the bits of each number and gives wrong results. Apply~only to boolean masks. - Mixing
&and|without parentheses and getting a grouping you did not intend.
Exercise
Write one line that keeps the rows of df where the population is below 5000 thousand and the continent is either "Europe" or "Asia". Which cities does it return?
Show answer
df[(df["population_k"] < 5000) & (df["continent"].isin(["Europe", "Asia"]))] returns Oslo and Pune. An equivalent form uses (df["continent"] == "Europe") | (df["continent"] == "Asia") for the second condition, wrapped in its own parentheses.
Exercise
Why does df[(df["population_k"] > 3000) and (df["continent"] == "Asia")] fail, and how do you fix it?
Show answer
The and keyword needs one truth value for each whole Series, which pandas cannot give, so it raises a ValueError. Replace and with &, which compares the two masks row by row.