Sub topic 4
Cleaning and searching text with .str
This chapter assumes you can create a Series, know what a dtype is, and have met the string dtype and pd.NA in earlier chapters. You should also know basic Python string methods.
How the .str accessor works
The .str accessor is a namespace on a Series that holds vectorized versions of Python's string methods. Calling s.str.upper() applies upper to every element and returns a new Series. The original is not changed.
Each call returns a Series, so you can chain calls. A typical cleaning pipeline reads left to right.
Cleaning
The most common cleaning steps are trimming whitespace, normalizing case, and replacing characters.
import pandas as pd
s = pd.Series([" Alice ", "BOB", None, "carol "], dtype="string")
clean = s.str.strip().str.lower()
print(clean)
print(clean.str.len())The missing entry stays <NA> through every step. str.len() returns a nullable integer (Int64), so the missing entry is <NA> there as well.
Other cleaning methods you will use often:
| Method | Effect |
|---|---|
| `str.strip()`, `lstrip()`, `rstrip()` | Remove surrounding whitespace |
| `str.lower()`, `upper()`, `title()` | Change case |
| `str.replace(old, new, regex=...)` | Replace text |
| `str.pad()`, `str.zfill(width)` | Pad to a fixed width |
Searching
Searching methods return a boolean Series that you can use as a filter mask. The main ones are str.contains, str.startswith, and str.endswith.
import pandas as pd
s = pd.Series(["alpha", None, "gamma"], dtype="string")
print(s.str.upper())
mask = s.str.contains("a")
print(mask)
print(s[s.str.contains("a", na=False)])On a string column, mask has the nullable boolean dtype. The missing entry produces <NA>, not False, because pandas cannot say whether a missing value contains "a". The na=False argument replaces those results with False, so the mask is plain true or false and the filter behaves predictably.
Literal text versus regular expressions
str.contains treats the pattern as a regular expression by default. A pattern such as "a.c" matches "abc" because . means any character. str.replace defaults to regex=False in current pandas, but older versions defaulted to True, so set the argument explicitly.
import pandas as pd
s = pd.Series(["v1.2", "v1x2", "v10.2"], dtype="string")
print(s.str.contains("1.2", regex=False))
print(s.str.contains("1.2", regex=True))With regex=False, only "v1.2" matches. With regex=True, "v1x2" matches too. Choose one on purpose each time. If you search for user-supplied text, escape it first with re.escape or use regex=False.
Common errors
The accessor fails or misleads in a few predictable situations.
- Non-text column. On an integer column,
.strraisesAttributeError: Can only use .str accessor with string values!. Convert withastype("string")first. - Mixed object column. On an
objectcolumn that holds both strings and numbers,.str.upper()returnsNaNfor the non-strings and does not raise. Silent gaps like this are one reason to prefer thestringdtype. - Forgetting the assignment.
.strmethods never modify in place. Writedf["name"] = df["name"].str.strip(). - Unexpected mask dtype. On an
objectcolumn,containsreturnsobjectwithNaNfor missing entries, and using that mask to filter can raise an error. Thena=Falseargument avoids this on both dtypes.
Putting it together
This example cleans a column and keeps only the rows that match a prefix.
import pandas as pd
df = pd.DataFrame(
{"code": [" ID-7 ", "id-12", None, "XY-3"]},
dtype="string",
)
df["code"] = df["code"].str.strip().str.upper()
ids = df[df["code"].str.startswith("ID-", na=False)]
print(ids)The result keeps ID-7 and ID-12. The missing row and XY-3 are dropped.
Exercise
A string column s contains "Red", "red ", None, and "RED". You run s.str.lower().str.contains("red") and use the result directly as a filter. What does the mask contain for the missing entry, and how do you change the code so the filter treats missing values as non-matches?
Show answer
The mask holds <NA> for the missing entry, because the result has the nullable boolean dtype and a missing value cannot be tested. Pass na=False, as in s.str.lower().str.contains("red", na=False), so the missing entry becomes False. Adding .str.strip() before contains is optional, because "red " still contains "red".