Text columns need cleaning — trimming whitespace, fixing case, splitting, extracting. The .str accessor applies Python string methods to a whole column at once, vectorised.
Cleaning text
df["name"].str.strip() # trim whitespacedf["name"].str.lower() # lowercasedf["name"].str.title() # Title Casedf["email"].str.contains("@") # boolean maskdf["code"].str.startswith("PY")
Splitting & extracting
df["email"].str.split("@").str[1] # the domaindf["phone"].str.replace("-", "") # strip separatorsdf["id"].str.extract(r"(\d+)") # pull digits with a regex
Key takeaways
- 01The .str accessor applies string methods to a whole column, vectorised.
- 02Clean with strip/lower/title; test with contains/startswith.
- 03split, extract (regex) and replace parse and transform text.
- 04Chain .str calls to build readable cleaning pipelines.
