Sub topic 7
Cleaning and splitting text with .str
This chapter assumes you can build a DataFrame, select a column by name, and assign a new column with df["name"] = .... You should also know that a column is a Series and that the earlier chapters' vectorized operations work on a whole column at once. Basic regular expressions help in the second half but are explained as they appear.
What the .str accessor does
Text columns usually need work before they are usable. They have stray spaces, inconsistent capitalization, and several facts packed into one string. Python's string methods such as "abc".strip() work on one string at a time. They do not work on a Series.
The .str accessor fixes this. s.str.strip() applies strip to every element and returns a new Series with the same index. You then assign that Series to a column, as with any other derived column.
import pandas as pd
raw = pd.DataFrame({
"name": [" Ann Lee", "bob ray ", None, "CARLA DIAZ"],
"email": ["[email protected]", " [email protected]", "[email protected] ", None],
})
raw["name_clean"] = (
raw["name"]
.str.strip()
.str.replace(r"\s+", " ", regex=True)
.str.title()
)
raw["email_clean"] = raw["email"].str.strip().str.lower()
print(raw[["name_clean", "email_clean"]])Each step returns a Series, so the steps chain. Here the pipeline removes outer whitespace, collapses runs of inner whitespace into one space, and fixes the capitalization. The missing name stays missing instead of raising an error.
Common cleaning methods
The methods you will use most often mirror Python's built-in string methods.
| Method | Purpose |
|---|---|
| `str.strip()`, `lstrip()`, `rstrip()` | Remove whitespace, or given characters, from the ends |
| `str.lower()`, `upper()`, `title()` | Change capitalization |
| `str.replace(pat, repl, regex=...)` | Substitute text |
| `str.len()` | Number of characters, as integers |
| `str.contains(pat)` | Boolean mask for a match |
| `str.startswith(x)`, `endswith(x)` | Boolean masks for a prefix or suffix |
| `str.zfill(n)` | Pad numeric text with leading zeros |
Two details cause most of the bugs with str.replace and str.contains.
- Regex defaults differ.
str.containstreats its pattern as a regular expression by default.str.replacetreats it as plain text by default in current pandas. Stateregex=Trueorregex=Falseexplicitly so the code reads the same on any version. - Special characters. In a regex,
.,$,(and+have special meanings. If you want a literal dollar sign, either passregex=Falseor put it in a character class such as[$].
A common use is turning formatted prices into numbers:
prices = pd.Series(["$1,200.50", "$35.00", None])
cleaned = prices.str.replace(r"[$,]", "", regex=True)
print(cleaned.astype(float))The character class [$,] matches either a dollar sign or a comma, so both are removed. The None becomes NaN, and astype(float) accepts that. If some strings might not parse, use pd.to_numeric(..., errors="coerce") as shown in the type-conversion chapter.
Filtering with boolean masks
str.contains, startswith and endswith return boolean Series. You can use them to select rows or to create flag columns.
notes = pd.Series(["Paid in full", "refund requested", None, "REFUND done"])
is_refund = notes.str.contains("refund", case=False, na=False)
print(is_refund)The na=False argument matters. Without it, a missing note produces a missing value in the mask. Using that mask to index a DataFrame then raises an error, because a boolean index cannot contain missing values. Setting na=False says that a missing note does not match. Use na=True only if you deliberately want missing values to count as matches.
Splitting text into pieces
str.split breaks each string at a delimiter. By default it returns a Series of lists, one list per row. Two patterns turn that into something usable.
Take one piece by position. Index the lists with .str[i]. This works because the accessor also handles list elements.
raw["domain"] = raw["email_clean"].str.split("@").str[1]
print(raw[["email_clean", "domain"]])Rows with a missing email give a missing domain. A string with no @ has a list of length one, so .str[1] returns NaN for it instead of raising an IndexError.
Expand into several columns. Pass expand=True to get a DataFrame with one column per piece. Use n=1 to limit the number of splits, so a name with a middle part still produces exactly two columns.
parts = raw["name_clean"].str.split(" ", n=1, expand=True)
parts.columns = ["first_name", "last_name"]
raw = raw.join(parts)
print(raw[["name_clean", "first_name", "last_name"]])The result has the same index as raw, so join aligns rows correctly. Without n=1, a longer name such as "Mary Ann Smith" would produce three columns and make the number of columns depend on the data. That is a common source of "columns must be same length" errors when you assign a fixed list of names. Setting n makes the shape predictable.
Use rsplit instead of split when the delimiter you care about is the last one, for example to separate a file extension from a name like "report.final.csv".
Extracting with regular expressions
str.split needs a consistent delimiter. When the structure is a pattern, str.extract is better. It applies a regex with capture groups and returns one column per group. Named groups, written (?P<name>...), become the column names.
orders = pd.DataFrame({"ref": ["ORD-2026-0042", "ORD-2025-0007", "bad", None]})
ref_parts = orders["ref"].str.extract(r"^ORD-(?P<year>\d{4})-(?P<seq>\d+)$")
orders = orders.join(ref_parts)
orders["year"] = pd.to_numeric(orders["year"])
print(orders)Rows that do not match, such as "bad", and missing rows both get NaN in every extracted column. That makes failed matches easy to find with orders["year"].isna().
The extracted values are still text, even when they look like digits. The pd.to_numeric call converts year to a number. Because some rows are NaN, the result is a float column, so you see 2026.0 and not 2026. If you need integers with gaps, convert to the nullable "Int64" type afterward.
str.extract returns only the first match in each string. If you need every match, str.extractall returns one row per match with a multi-level index. Use it only when a string may contain several matches.
How missing values and types behave
.str methods propagate missing values. A missing input gives a missing output, and string methods never raise errors on None or NaN. That is convenient, but it means problems can hide until later.
A few related behaviors are worth knowing:
.stronly works on text columns. Calling it on a numeric column raisesAttributeError: Can only use .str accessor with string values. Convert first withastype("string")orastype(str).astype(str)turns missing values into the literal text"nan"or"None". That text then passes every later check as ordinary data. The"string"dtype, with a lowercases, keeps missing values as<NA>instead. Prefer it when a column has gaps.- In an
objectcolumn that mixes strings and numbers,.strmethods returnNaNfor the non-string elements. This silently loses data, so checkdf["col"].map(type).value_counts()when results look too sparse. .strmethods return new Series and never change the original. Assign the result back, or the cleaning is lost.
Choosing between .str and apply
You can write df["name"].apply(lambda s: s.strip()), but .str is usually the better choice. It handles missing values for you, it is shorter, and it is generally faster because it is built for whole columns. Reserve apply for logic that no .str method expresses, such as calling a custom function on each string. The later chapter on apply covers that case.
Exercise
A column phone holds values like " (555) 123-4567 ", "555.987.6543", and missing entries. Write the steps to create a new column digits that holds only the digits, and a boolean column valid that is True only when digits has exactly 10 characters. Why should valid be built from digits using str.len() rather than from phone directly?
Show answer
Use df["digits"] = df["phone"].str.replace(r"\D", "", regex=True). The pattern \D matches any non-digit character, so spaces, parentheses, dots and dashes are all removed. Then use df["valid"] = df["digits"].str.len() == 10. Missing phone numbers give a missing digits value, so str.len() returns NaN and the comparison gives False, which is the right result for an invalid entry. Building valid from digits is better because the raw phone text has different formats and extra characters, so its length says nothing about how many digits it holds. Cleaning first makes the length check meaningful.