Cleaning Messy Data
Find and fix missing values, duplicates, wrong types, inconsistent text and impossible values, and decide when to drop, fill or flag a problem row.
Welcome back!
Step 1 of 12Learn
What dirty data looks like
A survey export lands on your desk. Within five minutes you find:
- an
agecolumn containing 34, "34", "thirty-four", 0 and 212; - a
countrycolumn with "USA", "U.S.", "United States" and " usa "; - 1,200 completely identical rows, because a form was submitted twice;
- an
incomecolumn where blanks, "N/A", "-" and 0 all seem to mean "no answer"; - dates such as "03/04/2026", which could be March 4 or April 3 depending on who typed them.
None of this is unusual. Data comes from people, forms, sensors and systems that were never designed together. Data cleaning means finding these problems and fixing them in a documented, repeatable way, so that the analysis reflects reality rather than data-entry accidents.
A good workflow:
- Profile the data:
info(),describe(),value_counts()on text columns,isna().sum()per column. - Fix types: numbers and dates stored as text.
- Standardize text: whitespace, capitalization, spelling variants.
- Handle missing values deliberately.
- Remove duplicates.
- Check validity: ranges, allowed categories, logical rules (an end date after a start date).
Keep the raw file untouched, do every fix in code, and record what you changed and why. Then anyone can rerun the cleaning when next month's export arrives.
Step 2 of 12Practice · Sort into groups
Classify each problem by type.
Tap an item, then tap its group (or drag it there).
Step 3 of 12Learn
Missing values in pandas
pandas marks missing data as NaN (for numbers), None, or NaT (for dates). Many datasets also hide missing values behind placeholders such as "N/A", "-", "?" or 999. Convert those first:
df = pd.read_csv("survey.csv", na_values=["N/A", "-", "?"])
df["age"] = df["age"].replace(999, np.nan)Then measure:
df.isna().sum() # missing count per column
df.isna().mean() * 100 # missing percentage per columnThree main strategies:
- Drop:
df.dropna(subset=["income"])removes rows missing income. Fine when few rows are affected and they're missing at random; risky when the missingness has a pattern, such as high earners skipping the question. - Fill (impute):
df["age"].fillna(df["age"].median())replaces missing ages with the median. Medians resist outliers better than means. For time series,ffill()carries the last known value forward. For categories, a value such as "Unknown" is often more honest than guessing. - Flag: add
df["income_missing"] = df["income"].isna()before filling, so the information that a value was missing isn't lost. That flag can itself be useful in a model.
One quirk to remember: NaN is not equal to anything, including itself. df[df["age"] == np.nan] returns nothing; always use isna() or notna().
Step 4 of 12Practice · Spot the mistake
Each line is meant to handle missing values in a numeric column score. Click the lines that won't work as intended.
Step 5 of 12Practice · Work it out
A column has values 10, 20, NaN, 30 and NaN. What does pandas return for its .mean()?
Step 6 of 12Try the calculator
How many rows survive dropna()?
If missing values in different columns occur independently, every extra column with gaps removes more rows. Change the rates to see how quickly a full dropna() shrinks a dataset. Real gaps are often correlated, so treat this as a rough guide.
- Rows left after dropna()
- 7,866
- Share of rows lost
- 21.3 %
Step 7 of 12Learn
Duplicates, text and impossible values
Duplicates. df.duplicated().sum() counts rows identical to an earlier row; df.drop_duplicates() removes them. Often the right test is a key rather than the whole row: df.drop_duplicates(subset=["email"], keep="last") keeps the most recent record per email. Decide which copy to keep deliberately.
Text. Standardize before grouping, or "Harbor", "harbor " and "HARBOR" become three stations:
df["country"] = df["country"].str.strip().str.upper()
df["country"] = df["country"].replace({"U.S.": "USA", "UNITED STATES": "USA"})Formatted numbers. Remove symbols, then convert:
df["price"] = pd.to_numeric(df["price"].str.replace("[$,]", "", regex=True), errors="coerce")errors="coerce" turns anything still unparseable into NaN instead of crashing, so check how many NaNs appeared afterwards.
Impossible values. Encode real-world rules as checks:
bad_age = ~df["age"].between(0, 110)
bad_dates = df["delivered"] < df["ordered"]
df.loc[bad_age, "age"] = np.nanNot every extreme value is an error. A $4 million house sale may be real; an age of 212 is not. Correct what you can verify, set clearly impossible values to missing, and investigate suspicious ones with the people who know the data.
Step 8 of 12Practice · Code challenge · Python
Write clean_prices(raw) that converts a list of messy price strings to floats. Strip whitespace and remove $ and , characters. Values that are empty, "N/A" or otherwise not numbers become None. Return the cleaned list.
clean_prices(["$1,200", " 15.50 ", "N/A", "", "abc", "7"])clean_prices(["$0.99"])clean_prices([])
Step 9 of 12Learn
Making cleaning repeatable
Cleaning done by clicking through a spreadsheet must be redone by hand every time new data arrives, and nobody can review exactly what was changed. Cleaning done in code can be rerun in seconds and checked line by line.
A simple structure works well: one function per concern, combined in a pipeline.
def fix_types(df):
return df.assign(price=pd.to_numeric(df["price"], errors="coerce"),
ordered=pd.to_datetime(df["ordered"]))
def standardize_text(df):
return df.assign(country=df["country"].str.strip().str.upper())
clean = raw.pipe(fix_types).pipe(standardize_text).drop_duplicates()Add checks that fail loudly when assumptions break, so problems surface the day they appear rather than months later:
assert clean["price"].ge(0).all(), "negative prices found"
assert clean["order_id"].is_unique, "duplicate order IDs"Log simple numbers at each stage, such as rows in, rows out and missing values per column, so a sudden change ("this month 30% of rows were dropped") is visible immediately.
Finally, keep three layers of data: raw (never edited), clean (output of the pipeline) and analysis tables built from the clean layer. When a mistake is found, you fix the pipeline and regenerate everything downstream.
Step 10 of 12Practice · True or false
Writing cleaning steps as code, with checks such as assertions, lets the same cleaning be rerun and reviewed whenever new data arrives.
Step 11 of 12Note
Step 12 of 12Practice · Select all that apply
A survey dataset has an income column with 8% missing values, mostly from respondents who skipped the question. Which actions are sound? Select all that apply.
Select all that apply.
Lesson complete!