Sub topic 7
Cleaning and splitting text with .str
This chapter assumes you can build a DataFrame, select a column by name, and know that a column is a Series. It also assumes you know that vectorized operations act on a whole column at once. Text columns need their own tools, because Python string methods do not work directly on a Series.
Why you need the .str accessor
Calling df["name"].strip() fails, because a Series has no strip method. The .str accessor applies a string method to every element and returns a new Series. You can assign that Series to a new column.
import pandas as pd
people = pd.DataFrame({
"name": [" ann lee", "BOB RAY ", "cy Wu"],
"email": ["[email protected]", "[email protected]", None],
})
people["name_clean"] = people["name"].str.strip().str.title()
print(people)Each .str call returns a Series, so you can chain calls. Here strip() removes surrounding whitespace and title() capitalizes each word.
Common cleaning methods
| Method | What it does |
|---|---|
| `str.strip()` | Removes leading and trailing whitespace |
| `str.lower()`, `str.upper()`, `str.title()` | Changes case |
| `str.replace(pat, repl, regex=False)` | Replaces text |
| `str.contains(pat)` | Returns True or False for each row |
| `str.len()` | Returns the length of each string |
str.replace treats the pattern as a literal string in current pandas, but pass regex=True or regex=False explicitly so the intent is clear. The text "cy Wu" above has two spaces between words. This regex collapses them:
people["name_clean"] = (
people["name"]
.str.strip()
.str.replace(r"\s+", " ", regex=True)
.str.title()
)
print(people["name_clean"])Splitting text into columns
str.split breaks each string into a list. Add expand=True to get one column per piece, and n=1 to limit the number of splits.
parts = people["name_clean"].str.split(" ", n=1, expand=True)
people["first"] = parts[0]
people["last"] = parts[1]
people["domain"] = people["email"].str.split("@").str[1]
print(people[["first", "last", "domain"]])The expression .str[1] picks the item at position 1 from each list. The accessor works on lists as well as on strings. For pattern-based extraction, str.extract returns the first captured group of a regex:
people["tld"] = people["email"].str.extract(r"\.(\w+)$")Missing values
The row with None as its email does not raise an error. Every .str method returns NaN for a missing value, so the missing value flows into the new column. Methods that return True or False, such as str.contains, return NaN for those rows too. This breaks boolean filtering. Pass na=False to treat missing values as non-matches.
has_org = people["email"].str.contains(".org", regex=False, na=False)
print(people[has_org])Common errors
- AttributeError: Can only use .str accessor with string values. The column holds numbers or dates. Convert it first with
astype(str), but note that this turnsNaNinto the text"nan". - Forgetting to assign the result.
.strmethods return new Series and never change the original. - Unescaped regex characters. In
str.contains(".org")the dot matches any character. Useregex=Falsefor literal text.
Exercise
A column code contains values such as " ab-12 " and "CD-7". Write code that creates prefix with the upper-case letters before the hyphen. Then create number with the digits after it, as integers.
Show answer
cleaned = df["code"].str.strip() df["prefix"] = cleaned.str.split("-").str[0].str.upper() df["number"] = cleaned.str.split("-").str[1].astype(int)
Exercise
Why does df[df["email"].str.contains("org")] raise an error when the email column has missing values, and how do you fix it?
Show answer
The missing values give NaN in the Boolean mask, and pandas cannot use a mask that contains NaN for indexing. Pass na=False to str.contains so missing rows count as non-matches.