Sub topic 8
Helpers for Common Filters: isin, between, and String Methods
This chapter assumes you can write a boolean mask such as df["population_k"] > 3000. It also assumes you know how to combine masks with &, |, and ~. Here you will learn three families of helpers that build masks for you: isin, between, and the .str accessor. They replace long chains of comparisons with one readable call. They also have edge cases that cause most of the errors people hit with them.
Why use helpers
Every helper in this chapter returns a boolean Series with the same index as the column it was called on. You use it exactly like a hand-written comparison: put it inside df[...] or df.loc[...], or combine it with other masks.
The examples use the same cities DataFrame as earlier chapters. Run this block first. Later blocks continue from it.
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"],
)Matching a list of values with isin
Series.isin(values) is True where an element equals any item in values. It replaces a chain of == comparisons joined by |.
asia_or_africa = df["continent"].isin(["Asia", "Africa"])
print(df[asia_or_africa])This returns Pune and Cairo. To keep everything except the listed values, negate the mask with ~:
print(df[~df["continent"].isin(["South America"])])This returns Oslo, Pune, and Cairo. isin accepts any list-like, including a set, a tuple, or another Series. A common pattern is to filter one table by the keys found in another:
wanted = {"Lima", "Quito"}
print(df[df["city"].isin(wanted)])Keep these points in mind:
isintests equality only. It does not do partial matches. Use.str.containsfor those.- You must pass a list-like.
isin("Asia")raises aTypeErrorbecause a bare string is not a list of values. - Matching is case-sensitive for strings.
"asia"does not match"Asia".
Numeric and date ranges with between
Series.between(left, right) is True where left <= value <= right. Both ends are included by default, which makes it different from a slice with .iloc.
print(df[df["population_k"].between(2500, 5000)])This returns Pune (3124) and Quito (2800). It is the same as (x >= 2500) & (x <= 5000), with the column named once.
The inclusive argument controls the endpoints. It accepts "both" (the default), "neither", "left", and "right".
mask = df["population_k"].between(2800, 10092, inclusive="neither")
print(df[mask])Only Pune appears. Quito (2800) and Lima (10092) sit exactly on the excluded endpoints, and Cairo is above the range.
between also works on datetime columns, where the bounds can be strings that pandas can parse as dates. Rows with missing values give False, because a comparison with NaN is never true.
Text filters with the .str accessor
Text columns have an accessor named .str. It applies a string method to every element and returns a Series. Many of those methods return booleans, which makes them mask builders.
| Method | Returns True when | Notes |
|---|---|---|
| `.str.startswith("Q")` | the text begins with the prefix | Plain text, not a regex |
| `.str.endswith("o")` | the text ends with the suffix | Plain text, not a regex |
| `.str.contains("ai")` | the text includes the pattern | Pattern is a regex by default |
| `.str.match("^[LQ]")` | the pattern matches at the start | Always a regex |
| `.str.fullmatch("Oslo")` | the whole text matches | Always a regex |
| `.str.len() > 4` | the length passes a comparison | Returns numbers, so compare it |
print(df[df["city"].str.startswith("Q")])
print(df[df["city"].str.contains("[ao]$")])
print(df[df["city"].str.len() > 4])The second line uses a regular expression, [ao]$, meaning "ends with a or o". It returns Oslo, Lima, Cairo, and Quito. The third line keeps cities with more than four letters, which are Cairo and Quito.
Case, regular expressions, and literal text
contains has three arguments you will use often:
case=Falseignores case.regex=Falsetreats the pattern as literal text.na=Falsedecides what missing values return (covered below).
Because regex=True is the default, characters such as (, ., +, and ? have special meaning. Searching for a literal parenthesis without turning regex off raises an error:
labels = pd.Series(["Oslo (old)", "Lima", "Pune (new)"])
print(labels.str.contains("(", regex=False)) # works: literal match
# labels.str.contains("(") # re.error: missing ), unterminated subpatternThe same applies to . in a pattern such as "St.", which silently matches any character after St. If you mean literal text, set regex=False.
Missing values in text columns
A text column that contains None or NaN is the most common cause of errors with .str. The string methods return a missing value for those rows, so the "mask" has three states: True, False, and NaN. Indexing with it fails.
people = pd.DataFrame({"name": ["Ana Diaz", "Bo Li", None, "Cy Ng"]})
mask = people["name"].str.contains("^b", case=False, na=False)
print(people[mask])With na=False, the missing row counts as "no match", and only Bo Li is returned. Without it, people[people["name"].str.contains("^b", case=False)] raises ValueError: Cannot mask with non-boolean array containing NA / NaN values. Use na=True if you want missing rows kept instead.
The startswith, endswith, and match methods take na as well. To filter on missingness itself, use isna() and notna() as described in the previous chapter.
.str also raises AttributeError: Can only use .str accessor with string values when the column holds numbers. Convert first with df["code"].astype("string") or .astype(str). Be aware that astype(str) turns missing values into the text "nan", so astype("string") is safer.
Combining helpers
Helper masks combine like any other masks. Give each its own variable, or wrap each one in parentheses, because & and | bind more tightly than comparison operators.
in_range = df["population_k"].between(2500, 11000)
not_europe = ~df["continent"].isin(["Europe"])
has_i = df["city"].str.contains("i", case=False)
print(df[in_range & not_europe & has_i])All three masks share the DataFrame's index, so pandas aligns them row by row. The result is Lima, Cairo, and Quito. Pune contains no i, so the last mask removes it.
Helpers also work inside .loc when you select columns at the same time:
print(df.loc[df["continent"].isin(["Asia", "Africa"]), ["city", "country"]])Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError` from `isin("Asia")` | A string was passed instead of a list | Pass `["Asia"]` |
| Empty result from `between(5000, 2500)` | Bounds are in the wrong order | Put the lower bound first |
| `ValueError` about NA / NaN in a mask | `.str` method on a column with missing values | Add `na=False` |
| `AttributeError` about `.str` | The column is numeric | Convert with `astype("string")` |
| `re.error` from `contains` | Special character in a regex | Escape it or use `regex=False` |
| Case variants missed | Matching is case-sensitive | Use `case=False`, or call `.str.lower()` first |
Exercise
Using the cities DataFrame, write one expression that returns the rows where the continent is South America or Europe, the population is strictly between 700 and 10092 (neither endpoint included), and the city name contains the letter "s" in any case. Which rows come back?
Show answer
df[df["continent"].isin(["South America", "Europe"]) & df["population_k"].between(700, 10092, inclusive="neither") & df["city"].str.contains("s", case=False)] returns only Oslo. Lima is excluded because 10092 is an excluded endpoint, and it has no "s". Quito has no "s". Oslo has population 709, which lies between 700 and 10092, and its name contains "s".
Exercise
A column called "email" contains some missing values. You run df[df["email"].str.endswith(".org")] and get a ValueError about NA / NaN. Rewrite the filter so rows with a missing email are dropped, and explain why the error occurred.
Show answer
Use df[df["email"].str.endswith(".org", na=False)]. The string method returns NaN for missing rows, so the result is not a pure boolean mask and pandas refuses to index with it. Setting na=False turns the missing results into False, so those rows are excluded.