PY-401 · Cleaning messy data
Cleaning text columns
⏱ 8 min 🐍 Real Python 3 🎬 Animated ✓ Completed
⚡ The 30-second answer
Text columns are cleaned with the .str accessor, which runs a string method on every value: df["name"].str.strip().str.title() removes extra spaces and fixes capitals in one line. .str.replace(r"\D", "", regex=True) removes every non-digit, and .str.contains("Rao") finds matching rows. Clean text before you group or count, or "Pune" and "pune " end up as two cities.
- Strip spaces and fix capitals
- Remove unwanted characters with replace
- Find rows with contains
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import pandas as pdpeople = pd.DataFrame({"name": [" asha RAO", "Ben smith ", "CHEN li"],"city": ["pune", "Pune ", "LEEDS"],"phone": ["+91-98450 12345", "(0113) 496 0000", "98450-55555"],})people["name"] = people["name"].str.strip().str.title()people["city"] = people["city"].str.strip().str.capitalize()people["phone"] = people["phone"].str.replace(r"\D", "", regex=True)print(people)print(people["city"].value_counts().to_dict())print(people[people["name"].str.contains("Rao")]["name"].tolist())
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
name city phone
0 Asha Rao Pune 919845012345
1 Ben Smith Pune 01134960000
2 Chen Li Leeds 9845055555
{'Pune': 2, 'Leeds': 1}
['Asha Rao'] 🎯 Clean the "city" column so each value has no outer spaces and is in title case, then set counts to products["city"].value_counts().to_dict().
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
products["city"] = products["city"].str.strip().str.title() then counts = products["city"].value_counts().to_dict()
- The problemA sign-up form lets people type their city. The report shows "pune", "Pune " and "PUNE" as three different cities, and the Pune team looks smaller than it is.
- The Python idea
df["col"].str.strip().str.title()Text columns are cleaned with the.straccessor, which runs a string method on every value:df["name"].str.strip().str.title()removes extra spaces and fixes capitals in one line. - In real lifeA delivery company strips and upper-cases every postcode before matching addresses to depots, so "ls1 4ap " and "LS1 4AP" go to the same van.
Start with a question
A sign-up form lets people type their city. The report shows "pune", "Pune " and "PUNE" as three different cities, and the Pune team looks smaller than it is.
Grouping, counting and joining all match text exactly. One stray space or capital letter splits a group in two and gives wrong numbers.
Explain it like I'm 10
Imagine everyone wrote their name on the register in their own style: some in capitals, some with big gaps. Cleaning text is rewriting them all neatly in the same style.
The technical explanation
.str gives a column the string methods you know from PY-101: strip, lower, upper, title, replace, startswith and more.
Methods chain: .str.strip().str.lower() removes spaces, then lowers the case.
.str.replace(pattern, "", regex=True) uses a regular expression. \D means "any character that is not a digit".
.str.contains("text") returns True/False per row, so it works as a filter. Add case=False to ignore capitals.
Syntax
df["col"].str.strip().str.title()
df["col"].str.replace(r"\D", "", regex=True)
df[df["col"].str.contains("text", case=False)] Real-world scenario
A delivery company strips and upper-cases every postcode before matching addresses to depots, so "ls1 4ap " and "LS1 4AP" go to the same van.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
🏆 Every lesson counts toward your certificate Next: groupby: totals per group →Questions people ask
How do I remove spaces from a pandas column?
Use df["col"].str.strip() to remove spaces at both ends. To remove every space, use df["col"].str.replace(" ", "").
How do I make text lowercase in pandas?
Use df["col"].str.lower(). Lowercasing before grouping or joining means "Pune" and "PUNE" match.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner How do I remove spaces from a pandas column?
Use df["col"].str.strip() to remove spaces at both ends. To remove every space, use df["col"].str.replace(" ", "").
beginner How do I make text lowercase in pandas?
Use df["col"].str.lower(). Lowercasing before grouping or joining means "Pune" and "PUNE" match.
intermediate What does .str do on a pandas column?
Runs a string method on every value. .str applies string methods value by value.
intermediate Which removes spaces at both ends?
.str.strip(). strip removes leading and trailing whitespace.
Quick revision
Remember
- Strip spaces and fix capitals
- Remove unwanted characters with replace
- Find rows with contains
.strmethods return NaN for missing values instead of crashing, so you can clean first and handle gaps afterwards.
Syntax
df["col"].str.strip().str.title()
df["col"].str.replace(r"\D", "", regex=True)
df[df["col"].str.contains("text", case=False)] Official documentation
- Working with text data (docs.python.org)