Sub topic 2
Cleaning and searching text with `.str`
Assume you know basic Python strings, regular expressions, pandas Series and DataFrame objects, and pandas dtypes. The .str accessor applies vectorized string operations to every value in a Series.
import pandas as pd
names = pd.Series(
[" Ada Lovelace ", "ALAN TURING", None],
dtype="string",
)
clean = names.str.strip().str.title()
print(clean)
print(clean.isna().tolist())strip() removes surrounding whitespace. title() changes capitalization. Missing values remain missing instead of becoming the text "None".
Literal and regex matching
String methods often accept either literal text or a regular expression. A regular expression is a pattern that can match several forms of text. Make the choice explicit:
codes = pd.Series(["id-001", "id-042", "unknown"], dtype="string")
literal = codes.str.contains("id-", regex=False, na=False)
pattern = codes.str.contains(r"^id-\d+$", regex=True, na=False)
print(codes[literal].tolist())
print(codes[pattern].tolist())The literal search looks for the exact characters id-. The regular expression requires the whole value to contain id- followed by one or more digits. na=False makes missing values false in a filtering mask.
Splitting and extracting into columns
Use split when separators define fields. Use extract when a regular expression contains capture groups.
people = pd.DataFrame(
{"name": ["Ada Lovelace", "Alan Turing", "Grace Hopper"]},
dtype="string",
)
people[["first", "last"]] = people["name"].str.split(
" ", n=1, expand=True
)
people["number"] = people["name"].str.extract(
r"(\d+)", expand=False
)
print(people)With expand=True, split returns a DataFrame. extract returns the captured text and gives <NA> when no match exists.
Converting existing columns
Convert text columns explicitly instead of relying on object. The dedicated string dtype gives consistent missing-value behavior.
df = pd.DataFrame({"city": ["Oslo", "Lima", None]})
df["city"] = df["city"].astype("string")
# Or convert several columns and infer nullable dtypes:
converted = df.convert_dtypes()
print(converted.dtypes)convert_dtypes() can also change integer columns to nullable Int64. Check the result when downstream code depends on exact dtypes.
Exercise
Which argument makes str.contains treat a search term as ordinary text and missing values as non-matches?
Show answer
Use regex=False for literal matching and na=False for filtering.