← Data analysis with Python

Fixing types, text and duplicates

Turn "$4.50" into 4.5, tidy messy labels, and remove repeated rows.

Start this lesson

Messy data often hides in plain sight. A price column with "$" signs is stored as text, so math fails or gives nonsense. A city typed as "Austin", "austin " and " AUSTIN" counts as three different cities. And the same row entered twice doubles its effect. pandas has tools for each: .str.replace and .astype(float) or pd.to_numeric to fix numbers, .str.strip() and .str.title() to tidy text, and drop_duplicates() to remove repeated rows.

import pandas as pd

orders = pd.DataFrame({
    "city": ["Austin", "austin ", " AUSTIN", "Denver"],
    "price": ["$4.50", "$3.00", "n/a", "$5.25"],
})
orders["city"] = orders["city"].str.strip().str.title()
orders["price"] = pd.to_numeric(orders["price"].str.replace("$", "", regex=False), errors="coerce")
print(orders)
print(orders["city"].nunique(), orders["price"].sum())

strip() removes spaces at the ends, title() makes "AUSTIN" into "Austin", so there are now 2 cities. After removing "$", to_numeric converts the text; errors="coerce" turns "n/a" into NaN instead of crashing.

.str gives you string methods that work on every value in a column at once.

.astype(int) and .astype(float) convert a whole column, but they fail if any value cannot be converted. pd.to_numeric(..., errors="coerce") is more forgiving.

drop_duplicates() keeps the first copy of each fully repeated row. Check df.duplicated().sum() first to see how many there are.