String cleaning
The .str accessor applies string methods to a whole column at once.
In this page:
Syntax
df["column"].str.lower()
df["column"].str.strip()
df["column"].str.contains("text")
String cleaning
Access string methods through df["col"].str: lower, upper, strip, contains, startswith, len and more. They work on every value and skip missing ones. Regular expressions are supported in contains, replace and extract.
Note:
str.title() capitalizes each word, handy for names.
Example: String cleaning
import pandas as pd
s = pd.Series([" alice SMITH ", "BOB jones", None])
print(s.str.strip().str.title())
print(s.str.contains("bob", case=False))
print(s.str.len())
# Output:
# 0 Alice Smith
# 1 Bob Jones
# 2 None
# dtype: object
# 0 False
# 1 True
# 2 None
# dtype: object
# 0 14.0
# 1 9.0
# 2 NaN
# dtype: float64
Related Topics
Common Mistakes
- Calling string methods directly on the Series
- Ignoring NaN in text columns
- Forgetting str methods return new Series
Chapter Summary
- Use the .str accessor
- Methods run on every value
- NaN is skipped safely
- Regex is supported
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: