Lesson 3: Cleaning Messy Data
Real data is messy. Values are missing, dates are written in three different formats, the same school appears as "St Mary's", "St. Marys" and "ST MARYS", and one student's height is recorded as 175 centimetres while another's is 1.75 metres. Cleaning is the unglamorous work of finding and fixing these problems, and it often takes more time than the analysis itself. Skipping it does not save time; it moves the errors into the results, where they are harder to spot.
Start by looking. Print the first rows, count how many values are missing in each column, and check the range of each number: a negative age, a test score of 250 out of 100, or a year of 1900 in a school survey are all signals that something is wrong. Plot the data too — a single wild point on a chart is often a typo that a table would hide. The goal of this first look is a list of problems, not fixes yet.
Missing Values and Duplicates
Missing values need a decision, and the decision should depend on why they are missing. If a few rows are missing a value at random, dropping those rows is often fine. If many rows are missing the same column, the column itself may be unreliable. Filling in missing values with the average is tempting but dangerous: it shrinks the spread of the data and pretends you know something you do not. Whatever you choose, record it — the reader of your analysis needs to know how much data was missing and what you did about it.
Duplicates are another common problem: the same person, school or transaction recorded twice. Sometimes the fix is to drop the extra copy; sometimes the two copies disagree, and you must decide which to trust. The same goes for inconsistent labels: pick one spelling, one format, one unit, and apply it everywhere. A small table of your cleaning decisions — what you changed and why — is one of the most useful things in a data project.
Cleaning in pandas
In Python, the pandas library makes cleaning concrete. The code below loads a CSV file, shows the shape and missing values, drops exact duplicates, and fills a missing score with the column's median rather than its mean, because the median is less affected by extreme values. It is a short, repeatable script — and because it is a script, the same cleaning can be run again on new data, and anyone can check what was done.
import pandas as pd
df = pd.read_csv("survey.csv")
print(df.shape) # how many rows and columns?
print(df.isna().sum()) # missing values per column
df = df.drop_duplicates()
df["score"] = df["score"].fillna(df["score"].median())
df.to_csv("survey_clean.csv", index=False)
Cleaning is not about making the data look tidy; it is about making it trustworthy. Every fix should be traceable, every judgement recorded, and the raw data kept untouched. An analysis built on cleaned data you can defend is worth far more than a fancier analysis built on data you cannot.
The Cost of Bad Data
Bad data is expensive in a way that is easy to underestimate. A single mislabelled column can invalidate weeks of analysis, because every conclusion downstream inherits the error. A duplicated set of records can make a result look twice as strong as it is. And a silent error — a unit changed halfway through a dataset, or a code that meant one thing in 2023 and another in 2024 — can produce a confident, wrong answer that nobody questions, because the analysis itself ran perfectly. The cleaning stage exists to catch these errors before they become conclusions, and it is the cheapest place to catch them.
There is a useful rule for deciding how much cleaning is enough: clean until the remaining errors are smaller than the effect you are trying to measure. If you are looking for a difference of twenty points, a few stray values will not change the answer; if you are looking for a difference of two points, they might. That rule keeps cleaning proportionate: thorough where it matters, and not endless where it does not. And whatever you do, write it down — the cleaning log is part of the analysis, not an afterthought.
Key Terms
- Data cleaning
- Finding and fixing errors, missing values and inconsistencies in data.
- Missing value
- A blank or absent entry in a dataset.
- Duplicate
- The same record appearing more than once in a dataset.
- Median
- The middle value when data is ordered; less affected by extreme values than the mean.
- Outlier
- A value far from the rest of the data, which may be a real extreme or an error.
- CSV
- Comma-separated values: a plain-text file format for tables, readable by pandas.
Discussion Questions
- A test score of 250 out of 100 appears in your data. How do you decide whether to fix it, drop it, or keep it?
- Filling missing values with the average shrinks the spread of the data. Why is that a problem for your conclusions?
- When would you keep a duplicate record instead of deleting it?
Practice Questions
- Why should cleaning happen on a copy, with the raw data kept untouched?
- What does
df.isna().sum()tell you? - Why might you fill a missing value with the median rather than the mean?
- Give two problems you might find in a first look at a dataset.
- What should you record about every cleaning decision?
Show answers
- So a mistake can always be undone and the original can be checked. If you clean the only copy, errors are permanent.
- How many missing values there are in each column. It is the first step in deciding what to do about them.
- Because the median is less affected by extreme values, so it is a safer typical value when the data has outliers.
- Any two of: missing values, duplicates, inconsistent spellings or formats, values out of range (such as a negative age), or mixed units.
- What you changed and why — for example how many rows were dropped and how missing values were handled — so the work can be repeated and checked.