Text columns are where the mess lives — stray spaces, inconsistent case, values crammed together. The .str accessor applies Python string methods across a whole column at once, and pairs with regular expressions for serious extraction.
The .str accessor
Prefix any string operation with .str to vectorise it over the column:
df["name"].str.upper()df["name"].str.len()df["email"].str.contains("@example") # boolean maskdf["programme"].str.startswith("Data")df["city"].str.replace("Bengaluru", "Bangalore")
Cleaning text
The everyday normalisation that fixes most "why don't these match?" bugs:
df["city"] = (df["city"].str.strip() # trim whitespace.str.lower() # unify case.str.title()) # Title Case for display# Chained .str calls read top-to-bottom and stay vectorised.
Splitting & extracting
# Split "First Last" into two columnsdf[["first", "last"]] = df["name"].str.split(" ", expand=True)# Take the domain from an emaildf["domain"] = df["email"].str.split("@").str[1]# Get dummy/indicator columns from a multi-value fielddf["skills"].str.get_dummies(sep=",")
Regular expressions
For structured text, str.extract with a regex captures groups into columns — the precise tool for parsing codes, ids and patterns:
# Pull the year and a batch letter out of "2026-B batch"df[["year", "batch"]] = df["cohort"].str.extract(r"(\d{4})-([A-Z])")df["phone"].str.contains(r"^\+91", regex=True) # starts with +91df["text"].str.findall(r"#(\w+)") # all hashtags
Practice
On a messy text column: strip and unify case, then filter rows whose value contains a substring. Split a full-name column into first/last. Use str.extract with a regex to pull a year and code out of a combined field.
Key takeaways
- 01The .str accessor vectorises Python string methods over an entire column.
- 02Normalise with strip/lower/title to fix most text-matching bugs — chain .str calls.
- 03str.split(expand=True) splits into columns; .str[i] indexes the pieces.
- 04str.extract with a regex captures groups into new columns for structured text.
- 05Prefer simple methods; use regex only when needed and comment what it matches.
