Cleaning Messy Data in pandas: Missing Values, Duplicates, Types and Text
Turn a messy table into one you can trust: find NaN holes, drop or fill them (and assign the fill back), remove duplicates, convert bad numbers with errors="coerce", tidy text, then clean a small orders table end to end.
What you will learn
- Find missing values with isna().sum() and choose between dropna and fillna
- Assign fills back to the column instead of using inplace on a chained column
- Remove repeated rows with drop_duplicates, subset and keep
- Fix types with astype, to_datetime and to_numeric(errors="coerce"), and tidy text with .str
Before you start
- pandas Series and DataFrames
- pandas loc, iloc and filtering
The tables you've built so far were tidy. The data you get usually isn't. Think about a paper sign-up sheet after a lot of people have filled it in. Some skipped a box, so there are blanks. Some signed up twice. Somebody wrote N/A where a number should be, so you can't add that column up. And one person wrote LONDON in capitals while another wrote " london" with a space, so one city looks like two.
Fixing all this is called cleaning, or wrangling, and you do it before you trust any total. In pandas a blank box shows up as NaN, "not a number". Outputs below are from pandas 3.1.1.
Finding the holes
import pandas as pd
import numpy as np
df = pd.DataFrame({
"name": ["Alice", "Bob", "Carol", "Dev"],
"age": [25, np.nan, 30, 41],
"score": [np.nan, 88, 92, np.nan],
})
print(df)
print(df.isna())
print(df.isna().sum())
print(df.notna().sum())
name age score
0 Alice 25.0 NaN
1 Bob NaN 88.0
2 Carol 30.0 92.0
3 Dev 41.0 NaN
name age score
0 False False True
1 False True False
2 False False False
3 False False True
name 0
age 1
score 2
dtype: int64
name 4
age 3
score 2
dtype: int64
Notice the ages print as 25.0, not 25. NaN is a decimal kind of value, so one hole turns the whole column into decimals. isna() builds a True/False table of the same shape, and .sum() counts the Trues per column. isna().sum() is the first line to run on any new table.
Drop the rows, or fill the holes
clean = df.dropna()
print(clean)
print(df.dropna(subset=["age"]))
print(len(df), len(clean))
name age score
2 Carol 30.0 92.0
name age score
0 Alice 25.0 NaN
2 Carol 30.0 92.0
3 Dev 41.0 NaN
4 1
dropna() removes every row with at least one hole, and here that leaves only Carol (who keeps her label, 2). Three people lost when only some of their values were missing is too strong. With subset=["age"] only that column is checked, and just Bob goes. The last line shows df still has four rows: dropna returns a new table, which is why you store the result.
filled = df.fillna(0)
print(filled)
print(df.fillna({"age": 0, "score": -1}))
name age score
0 Alice 25.0 0.0
1 Bob 0.0 88.0
2 Carol 30.0 92.0
3 Dev 41.0 0.0
name age score
0 Alice 25.0 -1.0
1 Bob 0.0 88.0
2 Carol 30.0 92.0
3 Dev 41.0 -1.0
Everyone stays, but think about what it says: Bob's age is now 0 and Alice's score is 0, and neither is true. A constant is fine when it really means something, like zero items sold. A dictionary gives each column its own value.
Filling with the mean
print(df["age"].mean())
df["age"] = df["age"].fillna(df["age"].mean())
print(df)
means = df.mean(numeric_only=True)
smart = df.fillna(means)
print(smart)
32.0
name age score
0 Alice 25.0 NaN
1 Bob 32.0 88.0
2 Carol 30.0 92.0
3 Dev 41.0 NaN
name age score
0 Alice 25.0 90.0
1 Bob 32.0 88.0
2 Carol 30.0 92.0
3 Dev 41.0 90.0
mean() skips the hole and gives 32. fillna returns a new column, so you assign it back on the left. For every number column at once, df.mean(numeric_only=True) gives one mean per column (numeric_only because name is text). The mean is still a guess, though: Alice never scored 90.
Drop or fill?
- A few rows with holes and plenty of rows: dropping is usually fine.
- Can't afford to lose rows, or holes spread around: keep the rows and fill.
- Zero has a meaning: use a constant. A measurement like age or score: the mean is a sensible start.
Whichever you pick, it changes your results, so choose on purpose and write it down.
A fill that does nothing
You'll still see this line in older tutorials, and sometimes in AI-written code:
df = pd.DataFrame({
"name": ["Alice", "Bob", "Carol", "Dev"],
"age": [25, np.nan, 30, 41],
})
df["age"].fillna(0, inplace=True)
print(df)
name age
0 Alice 25.0
1 Bob NaN
2 Carol 30.0
3 Dev 41.0
S06L04_Cleaning\chained_fill.py:9: ChainedAssignmentError: A value is being set on a copy of a DataFrame or Series through chained assignment using an inplace method.
Such inplace method never works to update the original DataFrame or Series, because the intermediate object on which we are setting values always behaves as a copy (due to Copy-on-Write).
...
df["age"] behaves like a separate copy. inplace=True fills the copy, the copy is thrown away, and Bob's age is still NaN. The name says Error, but it's a warning, so the program carries on. In pandas 3, always assign it back: df["age"] = df["age"].fillna(0). This is the same trap as chained assignment in loc, iloc and filtering.
Repeated rows
df = pd.DataFrame({
"name": ["Alice", "Bob", "Alice", "Carol", "Bob"],
"score": [90, 85, 90, 88, 70],
})
print(df.duplicated())
clean = df.drop_duplicates()
print(clean)
by_name = df.drop_duplicates(subset=["name"])
print(by_name)
latest = df.drop_duplicates(subset=["name"], keep="last")
print(latest)
0 False
1 False
2 True
3 False
4 False
dtype: bool
name score
0 Alice 90
1 Bob 85
3 Carol 88
4 Bob 70
name score
0 Alice 90
1 Bob 85
3 Carol 88
name score
2 Alice 90
3 Carol 88
4 Bob 70
duplicated() checks each row against the rows above it. Row 2 matches row 0 exactly. The two Bobs have different scores, so both stay at first. With subset=["name"] only the name is compared. pandas keeps the first one by default; keep="last" keeps the last, useful when later rows are newer.
Changing a column's type
df = pd.DataFrame({
"qty": ["3", "5", "2", "7"],
"date": ["2024-01-01", "2024-02-15",
"2024-03-20", "2024-04-10"],
})
print(df.dtypes)
df["qty"] = df["qty"].astype(int)
df["date"] = pd.to_datetime(df["date"])
print(df.dtypes)
print(df["qty"].sum())
qty str
date str
dtype: object
qty int64
date datetime64[us]
dtype: object
17
Values in quotes came in as text. astype(int) and pd.to_datetime convert them, and you assign each back. Now the sum works: 3 + 5 + 2 + 7 = 17.
When one value won't convert
prices = pd.Series(["10", "20", "N/A", "40"])
print(prices.astype(float))
After a long traceback, the last line says:
ValueError: could not convert string to float: 'N/A'
One bad value out of four stops the whole conversion. For this, use pd.to_numeric with errors="coerce":
fixed = pd.to_numeric(prices, errors="coerce")
print(fixed)
print(fixed.dtype)
print(fixed.isna().sum())
print(fixed.fillna(fixed.mean()))
0 10.0
1 20.0
2 NaN
3 40.0
dtype: float64
float64
1
0 10.000000
1 20.000000
2 23.333333
3 40.000000
dtype: float64
Coerce means "force it": a value that can't convert becomes NaN instead of raising an error. Always check the isna().sum() count, because coerce won't warn you. Now it's an ordinary hole, and you already know how to fill it.
Tidying text
df = pd.DataFrame({
"city": [" new york", "LONDON ", "Paris",
"london", "paris "],
})
print(df["city"].duplicated().sum())
df["city"] = df["city"].str.strip().str.lower()
print(df["city"].tolist())
print(df["city"].duplicated().sum())
df["city"] = df["city"].str.title()
print(df.drop_duplicates())
0
['new york', 'london', 'paris', 'london', 'paris']
2
city
0 New York
1 London
2 Paris
To a computer these five strings are all different, so there are zero duplicates at first. str.strip removes spaces at both ends, str.lower makes everything small, and the same count now says 2. Tidy the text first, then look for duplicates.
Cleaning a small table end to end
import pandas as pd
import numpy as np
df = pd.DataFrame({
"customer": [" alice", "BOB ", "alice", "Carol"],
"amount": ["20", "N/A", "20", "35"],
"rating": [4.0, np.nan, 4.0, 5.0],
})
df["customer"] = df["customer"].str.strip().str.title()
amount = pd.to_numeric(df["amount"], errors="coerce")
df["amount"] = amount
df["amount"] = df["amount"].fillna(df["amount"].mean())
df["rating"] = df["rating"].fillna(df["rating"].mean())
df = df.drop_duplicates()
print(df)
print(df.dtypes)
print(df.isna().sum().sum())
customer amount rating
0 Alice 20.0 4.000000
1 Bob 25.0 4.333333
3 Carol 35.0 5.000000
customer str
amount float64
rating float64
dtype: object
0
Names tidied, N/A coerced to a hole and filled with the mean (25), Bob's rating filled with 4.33, and the two Alice rows, which only match after the text cleanup, reduced to one. isna().sum().sum() gives 0: no holes anywhere.
Here's something to notice: that mean of 25 was worked out while Alice's order was still counted twice. The order of your steps can change your numbers. When you prompt an AI tool to clean data, add one line: "Tell me every row you dropped and every value you filled." Then read that list, because only you know what's true for your data.
Recap
| Problem | Tool |
|---|---|
| Find holes | df.isna().sum() |
| Remove holes | df.dropna(), subset=[...] |
| Fill holes | df["c"] = df["c"].fillna(value or mean), assigned back |
| Repeated rows | drop_duplicates(subset=..., keep=...) |
| Wrong types | astype, pd.to_datetime, pd.to_numeric(errors="coerce") |
| Untidy text | .str.strip(), .str.lower(), .str.title() |
Try it yourself: in clean_orders.py, move drop_duplicates above the two fills, run it, and compare the means.
Next: groupby and merge.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
