Lesson 14 of 23
❮Prev Next❯

PY-401 · Cleaning messy data

Cleaning text columns

⏱ 8 min 🐍 Real Python 3 🎬 Animated

14of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    ⚡ 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.

    Cleaning text columns, running
    1. import pandas as pd
    2. people = pd.DataFrame({
    3. "name": [" asha RAO", "Ben smith ", "CHEN li"],
    4. "city": ["pune", "Pune ", "LEEDS"],
    5. "phone": ["+91-98450 12345", "(0113) 496 0000", "98450-55555"],
    6. })
    7. people["name"] = people["name"].str.strip().str.title()
    8. people["city"] = people["city"].str.strip().str.capitalize()
    9. people["phone"] = people["phone"].str.replace(r"\D", "", regex=True)
    10. print(people)
    11. print(people["city"].value_counts().to_dict())
    12. print(people[people["name"].str.contains("Rao")]["name"].tolist())
    Press ▶ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideadf["col"].str.strip().str.title()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.
    3. 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)]

    ▶ Run the example 🎬 Watch it come alive

    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.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What does .str do on a pandas column?
    2. 2. Which removes spaces at both ends?
    3. 3. "asha RAO" after .str.title() is…
    4. 4. Why clean "pune" and "Pune " before counting?
    5. 5. df[df.name.str.contains("li", case=False)] returns…

    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
    • .str methods 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