Module 2 · Beginner · Data cleaning

Fix wrong data types and messy text

Clean messy data in pandas: strip spaces, fix capitals and spelling variants, turn prices like "₹1,200" into numbers, map yes/no and split columns.

By theprogrammers team · · 5 min read

Data typed by people, or copied between systems, is full of small inconsistencies: "Kanpur", " kanpur" and "KANPUR"; prices written as "₹1,200" or "1200 Rs"; "Yes", "Y" and "yes" in the same column. To you they mean the same thing. To pandas they're different values, so counts split, groups multiply and sums fail.

This lesson shows how to fix the most common problems with pandas' .str methods, replace, map and to_numeric: stray spaces, capitals, spelling variants, numbers stored as text, yes/no columns and combined columns.

The messy data

import pandas as pd

raw = pd.DataFrame({
    "name": ["  Asha Verma", "ravi kumar ", "MEERA SINGH", "John  Dsouza"],
    "city": ["Kanpur", " kanpur", "KANPUR ", "Bombay"],
    "price": ["₹1,200", "850", "₹2,499.50", "1,050 Rs"],
    "member": ["Yes", "no", "Y", "N"],
    "phone": ["98765-43210", "9876543211", "+91 98765 43212", "98765 43213"],
})
print(raw)
print(raw["city"].value_counts())
           name     city      price member            phone
0    Asha Verma   Kanpur     ₹1,200    Yes      98765-43210
1   ravi kumar    kanpur        850     no       9876543211
2   MEERA SINGH  KANPUR   ₹2,499.50      Y  +91 98765 43212
3  John  Dsouza   Bombay   1,050 Rs      N      98765 43213
city
Kanpur     1
 kanpur    1
KANPUR     1
Bombay     1
Name: count, dtype: int64

Pandas sees four different cities where there are really two. Every column has problems, and every column is stored as text (object).

The .str accessor

Text columns have a .str accessor that applies a string method to every value at once:

MethodDoes" Kanpur " becomes
.str.strip()Removes spaces at both ends"Kanpur"
.str.lower() / .str.upper()Changes case" kanpur "
.str.title()Capitalises Each Word" Kanpur "
.str.replace(a, b)Replaces text
.str.contains(a)True/False for each value
.str.split(sep)Splits into parts
.str.len()Length of each value9

Methods chain, each applying to the result of the previous one.

Fix spaces and capitals

clean = raw.copy()
clean["city"] = clean["city"].str.strip().str.title()
clean["name"] = (clean["name"].str.strip()
                              .str.replace(r"\s+", " ", regex=True)
                              .str.title())
print(clean[["name", "city"]])
           name    city
0    Asha Verma  Kanpur
1    Ravi Kumar  Kanpur
2   Meera Singh  Kanpur
3   John Dsouza  Bombay

r"\s+" is a regular expression meaning "one or more spaces", so the double space in "John Dsouza" becomes one. regex=True tells pandas to treat the pattern that way.

Fix spelling variants and old names

Some differences need a lookup, not a formula. Bombay was renamed Mumbai in 1995; use replace with a dictionary of corrections:

clean["city"] = clean["city"].replace({"Bombay": "Mumbai", "Bangalore": "Bengaluru"})
print(clean["city"].value_counts())
city
Kanpur    3
Mumbai    1
Name: count, dtype: int64

Values not in the dictionary stay as they are. In real projects, build the corrections list by reading value_counts() and looking for variants.

Turn text into numbers

Prices with symbols, commas and units can't be converted directly. Remove everything that isn't a digit or a decimal point, then convert:

clean["price"] = pd.to_numeric(
    clean["price"].str.replace(r"[^0-9.]", "", regex=True),
    errors="coerce",
)
print(clean["price"])
print(clean["price"].sum())
0    1200.0
1     850.0
2    2499.5
3    1050.0
Name: price, dtype: float64
5599.5

[^0-9.] means "any character that is not a digit or a dot", so "₹", ",", " " and "Rs" all disappear. errors="coerce" turns anything still unconvertible into NaN; always check for new NaNs after converting. Data types, memory and categorical columns covers type conversion in more detail.

A caution: in some regions "1.200,50" means one thousand two hundred and a half. Know your data's format before stripping characters.

Yes/no columns into booleans

yes_no = {"yes": True, "y": True, "no": False, "n": False}
clean["member"] = clean["member"].str.strip().str.lower().map(yes_no)
print(clean["member"].tolist())
[True, False, True, False]

Normalise first (strip and lower), then map. Any value not in the dictionary becomes NaN, which is useful: it flags unexpected answers like "maybe" for you to check.

Standardise formats: phone numbers

Phone numbers arrive with dashes, spaces and country codes. Keep only digits, then take the last 10:

digits = clean["phone"].str.replace(r"\D", "", regex=True)
clean["phone"] = digits.str[-10:]
print(clean["phone"].tolist())
print(clean["phone"].str.len().eq(10).all())
['9876543210', '9876543211', '9876543212', '9876543213']
True

\D means "not a digit". .str[-10:] slices each string, just like slicing a Python string. The last line checks that every number now has exactly 10 digits, a habit worth keeping after any cleaning step.

Split one column into two

clean[["first_name", "last_name"]] = clean["name"].str.split(" ", n=1, expand=True)
print(clean[["name", "first_name", "last_name"]])
          name first_name last_name
0   Asha Verma       Asha     Verma
1   Ravi Kumar       Ravi     Kumar
2  Meera Singh      Meera     Singh
3  John Dsouza       John    Dsouza

n=1 splits only at the first space, so a name like "Asha Rani Verma" gives "Asha" and "Rani Verma". expand=True returns separate columns instead of lists. To combine columns, add them: df["first_name"] + " " + df["last_name"].

The cleaned result

print(clean[["name", "city", "price", "member", "phone"]])
print(clean[["price", "member"]].dtypes)
          name    city   price  member       phone
0   Asha Verma  Kanpur  1200.0    True  9876543210
1   Ravi Kumar  Kanpur   850.0   False  9876543211
2  Meera Singh  Kanpur  2499.5    True  9876543212
3  John Dsouza  Mumbai  1050.0   False  9876543213
price     float64
member       bool
dtype: object

Phone numbers stay as text on purpose: you never do arithmetic on them, and storing them as numbers would drop leading zeros in other formats.

A cleaning checklist for text columns

  1. value_counts() to see the variants.
  2. str.strip() to remove stray spaces.
  3. str.lower() or str.title() for consistent capitals.
  4. replace({...}) for known variants and spellings.
  5. str.replace(pattern, "", regex=True) to remove unwanted characters.
  6. pd.to_numeric(..., errors="coerce") or map({...}) to convert types.
  7. Check the result: value_counts() again, and count new NaNs.

Practice

  1. Clean pd.Series([" Delhi", "delhi ", "DELHI", "New Delhi"]) so the first three match.
Show the answer
s = pd.Series([" Delhi", "delhi ", "DELHI", "New Delhi"])
print(s.str.strip().str.title().value_counts())

"Delhi" appears 3 times. Whether "New Delhi" should also become "Delhi" is a domain decision.

  1. Convert pd.Series(["45%", "60 %", "7.5%"]) to the numbers 0.45, 0.6 and 0.075.
Show the answer
s = pd.Series(["45%", "60 %", "7.5%"])
print(pd.to_numeric(s.str.replace(r"[^0-9.]", "", regex=True)) / 100)
  1. After mapping a yes/no column, you find 12 new NaN values. What should you do?
Show the answer

Look at the original values in those rows, for example raw.loc[clean["member"].isna(), "member"].value_counts(). They're answers your dictionary didn't cover, such as "YES " or "true". Add them to the mapping, or decide they're genuinely unknown.

Interview questions

How do you clean inconsistent text values in pandas?

Use the .str accessor: strip for spaces, lower or title for case, replace with regular expressions for unwanted characters, and replace or map with a dictionary for known variants. Check with value_counts() before and after.

How do you convert a currency text column to numbers?

Remove non-numeric characters with str.replace(r"[^0-9.]", "", regex=True), then pd.to_numeric(..., errors="coerce"), and check for values that became NaN.

What is the difference between replace and map on a Series?

replace changes only the values found in the dictionary and leaves the others. map transforms every value through the dictionary or function, and values not found become NaN.

What to learn next

  1. Handle dates in clean and parse dates and times.
  2. Revisit remove duplicate rows, now that names are consistent.