How to Clean a Messy Dataset
Raw data rarely arrives in good shape. Columns have inconsistent spellings, dates come in three formats, some rows are duplicated, and others are missing key values. Any analysis built on top of that mess inherits its flaws.
Cleaning data is not glamorous, but it often decides whether the results can be trusted. The approach below works for spreadsheets, CSV exports and database extracts alike, and it focuses on a repeatable order of work.
Step one: keep the original untouched
Before changing anything, save a copy of the raw file and never edit it. Do your cleaning on a separate version, ideally with a script rather than manual edits. A script records exactly what you did and can be run again when new data arrives. Manual fixes in a spreadsheet are hard to repeat and easy to forget.
Step two: profile the data first
Get to know the dataset before fixing it. Look at the number of rows and columns, the type of each column, and a quick summary of values.
import pandas as pd
df = pd.read_csv("raw_data.csv")
print(df.shape)
print(df.dtypes)
print(df.describe(include="all"))
print(df.isna().sum())
This tells you which columns have missing values, which numeric columns hold strange ranges, and which text columns have far more unique values than expected. Profiling turns vague unease into a concrete list of problems.
Step three: remove duplicates
Duplicate rows inflate counts and skew averages. They appear when data is merged, exported twice or entered more than once.
Decide first what counts as a duplicate. Sometimes it means the entire row matches. Sometimes it means the same customer ID or order number appears twice with small differences. Inspect a few examples before deleting anything, and when two records conflict, choose a rule such as keeping the most recent.
Step four: fix structural problems
Structural errors are inconsistencies in how data is written. Common ones include:
- Inconsistent text: "New York," "new york" and "NY " should usually become one value. Trim extra spaces and standardize capitalization.
- Mixed date formats: convert every date to one standard format, such as year, month, day.
- Wrong data types: numbers stored as text, or IDs treated as numbers when they should be text (leading zeros can vanish).
- Units that differ: weights in both kilograms and pounds in the same column need converting to one unit.
- Stray symbols: currency signs, commas or footnote markers inside numeric fields.
- Misspellings and variants: map similar labels to a single agreed category.
A small mapping table for categories helps, since you can document it and reuse it.
Step five: handle missing values
Missing data needs a decision, and the right one depends on why it is missing.
- Leave it as missing when absence carries meaning, for instance a blank "end date" that means a subscription is still active.
- Drop the rows when only a small number are affected and the loss will not bias the results.
- Drop the column when most of its values are missing and it is not essential.
- Fill in a value (imputation) using the median, the most common category or a more careful model-based estimate.
Be careful with filling. Replacing blanks with an average can hide real variation and make the data look more certain than it is. Where it matters, add a flag column noting which values were filled, so later users know.
Step six: deal with outliers
Outliers are values far from the rest. Some are errors, such as an age of 250 or a negative quantity. Others are real, such as a very large genuine order.
Do not delete outliers automatically. Check them against the source or common sense. Fix obvious entry errors, keep genuine extremes, and consider whether your analysis method is sensitive to them. A median, for example, resists extreme values better than a mean.
Step seven: validate against rules
Write simple rules that clean data should satisfy, then test them:
- IDs are unique where they should be.
- Dates fall in a sensible range, and an end date is not before its start date.
- Required fields are present.
- Categories belong to an allowed list.
- Numeric values fall within plausible limits.
assert df["order_id"].is_unique
assert (df["end_date"] >= df["start_date"]).all()
Automated checks catch problems early and protect you the next time the data refreshes.
Step eight: document every change
Keep a short log of what you changed and why: which duplicates you removed, how you filled gaps, which categories you merged. Include counts, such as how many rows were affected. This lets colleagues trust the result and lets you explain it months later. It also reveals when cleaning removed too much.
Know when to stop
Perfect data does not exist. Clean until the data is fit for the question you are asking, and no further. A dataset used for a rough trend chart needs less polish than one feeding a financial report. Fixing the problems that affect your conclusions matters more than fixing every cosmetic flaw.
Frequently Asked Questions
Should I clean data in a spreadsheet or with code?
Spreadsheets are fine for small, one-off jobs. For anything repeated or large, code is better because the steps are recorded and can be rerun. Tools in Python, R or SQL all work well.
Is it better to delete rows with missing values or fill them in?
It depends on how much is missing and why. Deleting is simple when few rows are affected and the loss is random. Filling in helps preserve data but should be documented, since it adds assumptions.
How do I know the data is clean enough?
Run validation rules, check summaries against expectations, and confirm the data answers your question without obvious errors. If key results change a lot when you tweak a cleaning choice, investigate that choice more carefully.