Sub topic 8
Helpers for Common Filters: isin, between, and String Methods
This chapter assumes you can build a boolean mask from a comparison and combine masks with &, |, and ~. Here you will replace long chains of comparisons with three helpers that return masks directly.
Why helpers
A mask built from == and | gets long fast. Matching a column against five values means five comparisons joined by |. Pandas provides helpers that produce the same boolean Series with less code. Each helper returns a mask, so you pass it to df[...] or df.loc[...] and combine it with other masks as before.
The examples use this DataFrame.
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"],
)Membership with isin
Series.isin(values) is True where the element equals any item in values. It replaces a chain of == tests joined by |.
print(df[df["continent"].isin(["Asia", "Africa"])])This keeps Pune and Cairo. To keep everything else, negate the mask with ~.
print(df[~df["continent"].isin(["Asia", "Africa"])])Do not write df["continent"] in [...] or use or. Python's in, and, and or need a single truth value, and a Series has many, so pandas raises a ValueError.
Ranges with between
Series.between(left, right) tests a numeric range. It is inclusive on both ends by default.
print(df[df["population_k"].between(2500, 5000)])This keeps Pune (3124) and Quito (2800). The inclusive argument accepts "both", "neither", "left", or "right". Use inclusive="left" for a half-open range such as 2500 up to but not including 5000.
String methods with .str
The .str accessor applies string methods to every element and returns a Series. When the method returns booleans, the result is a mask.
print(df[df["city"].str.startswith("Q")])
print(df[df["city"].str.contains("o", case=False, na=False)])The second line keeps Oslo, Cairo, and Quito. Two details cause most errors:
str.containstreats its pattern as a regular expression by default. Passregex=Falseto search for literal text such as"."or"(".- Missing values give
NaNinstead ofTrueorFalse, and a mask containingNaNcannot be used for filtering. Passna=Falseso missing entries count as non-matches.
Choosing a helper
| Task | Helper | Example |
|---|---|---|
| Value is one of several | `isin` | `s.isin(["a", "b"])` |
| Number within a range | `between` | `s.between(1, 10)` |
| Text starts or ends with | `str.startswith`, `str.endswith` | `s.str.endswith("o")` |
| Text contains a pattern | `str.contains` | `s.str.contains("ito", na=False)` |
Combining helpers
Because every helper returns a mask, you can mix them with comparisons. Wrap each mask in its own parentheses, or give it a variable name, before using & or |.
mask = df["continent"].isin(["South America", "Europe"]) & df["population_k"].between(700, 3000)
print(df[mask])Exercise
Write a filter that keeps rows where the continent is "Europe" or "South America" and the population is between 700 and 3000 inclusive. Which cities remain, and why is Lima excluded?
Show answer
df[df["continent"].isin(["Europe", "South America"]) & df["population_k"].between(700, 3000)] keeps Oslo (709) and Quito (2800). Lima is in South America, but its population of 10092 is outside the range, so the between mask is False for it.