How to Clean a Messy Dataset for a Machine Learning Project

A practical, ordered checklist for cleaning a messy dataset before training a machine learning model: removing duplicates, fixing formats and units, handling missing values, checking outliers and label errors, avoiding leakage by splitting before cleaning, plus a small reusable pandas workflow and verification checks for the cleaned data.

Written by Projectech13 min readPublished
For Computer Science, IT and AI/ML students preparing real-world datasets for machine learning coursework and academic projects in Python with pandas. Topics: Python, pandas, Machine Learning, Data Cleaning
Blueprint-style technical illustration of data cleaning for machine learning: a messy table of scattered values being sorted into a clean structured dataset, with a magnifying glass, drawn in dark blue line art on white graph paper.
Illustration generated for this guide.
In this guide

How to Clean a Messy Dataset for a Machine Learning Project

Every machine learning project starts the same way: you download a dataset, open it, and discover it is a mess. Dates are written three different ways, half the rows have blank cells, one sensor column is in volts and another in millivolts, and the labels contain typos. The model you train on that data will learn the mess faithfully — garbage in, garbage out is not a slogan, it is the default outcome of skipping cleaning.

Cleaning is not glamorous work, but it is where most of the accuracy in a student project is actually won or lost. A careful cleaning pass on a small dataset usually improves results more than trying a fancier model, and it produces something a reviewer can trust: row counts before and after, a record of every decision, and a dataset you can defend. This guide gives you that process — a checklist in the right order, rules for when to drop, impute or flag, and a small pandas workflow you can reuse.

Quick Answer

Clean in this order: remove duplicates, fix formats and units, handle missing values, check outliers, then fix label errors. Split into train and test sets BEFORE any cleaning step that uses data statistics, or test data leaks into training and accuracy looks better than it is. Impute when a column is mostly complete, drop a column only when most of it is missing, and record every row you remove.

Why cleaning comes before modelling

A model learns patterns from whatever you feed it. If the same reading appears twice because of a logging error, the model treats it as two independent pieces of evidence. If missing temperatures were recorded as 0, the model learns that 0 degrees is a normal operating condition. If one column is in centimetres and another in metres, the model weighs them wrongly. None of these problems shows up as an error message — training runs fine, and the accuracy number looks plausible. The failure appears later, when the model meets real data and behaves unpredictably.

Cleaning is also where you learn what your data actually contains. The first pass through a messy dataset usually reveals that the collection process itself had problems — a sensor that drifted, a form that allowed free-text entries, a merge that duplicated rows. Finding those problems early lets you fix the collection or document the limitation, instead of discovering it during your demonstration.

The cleaning checklist, in order

Work through these steps in this order. Each step depends on the ones before it — for example, there is no point hunting outliers before you have fixed the units, because a value of 1,000 might be an outlier in metres and perfectly normal in millimetres.

1. Remove exact duplicates

Duplicated rows are the most common defect in student datasets, usually from a logging script that ran twice or a spreadsheet that was merged carelessly. Duplicates are dangerous because they leak across your train/test split: the same row can end up in both sets, and your model gets tested on data it already memorised. Remove exact duplicates first, and check for near-duplicates too — the same reading with a slightly different timestamp, or the same student record with a different capitalisation of a name.

2. Fix formats and units

Make every column consistent before you do anything statistical. Dates should be one format (ISO format, YYYY-MM-DD, is the safest). Categories should have one spelling each — "Yes", "yes" and "YES" are three different values to a computer. Units must match within a column: if a sensor column mixes volts and millivolts, convert one to the other and record which. Currency, percentages and decimal separators need the same treatment. This step is tedious and it is where most silent errors live.

3. Handle missing values

Missing data is normal; how you handle it is a modelling decision, not a chore. First, find out WHY values are missing. A sensor that failed for an hour leaves a block of missing rows — that is different from a survey question that respondents skipped, which is different again from a column that is empty because it does not apply to some rows. The reason should influence the fix.

The three options:

  • Drop the row. Safe when very few rows are affected (a few percent) and the missingness looks random. Dangerous when it removes a large share of the data, or when the missing rows share something in common — dropping every row where a sensor failed can delete exactly the failure cases your model most needs to learn.
  • Impute (fill in) the value. Use the median for numbers (it is less sensitive to outliers than the mean), the mode for categories, or a simple model-based fill for time series (forward fill, or interpolation between neighbours). Imputation keeps your rows, but it invents data — always add a flag column recording which values were imputed, so you can check later whether imputed rows behave differently.
  • Flag and keep. Sometimes the fact that a value is missing IS the information — a missing reading from a machine that stopped is a signal, not a gap. Keep the row, add a binary column marking the value as missing, and let the model use that signal.

As a rule of thumb for student projects: if a column is more than about half missing, consider dropping the column rather than the rows — imputing most of a column means the model is learning from invented values. If a row is missing most of its columns, drop the row. In between, impute and flag.

4. Check outliers

An outlier is a value far from the rest of the column. Some outliers are real — a genuine temperature spike when a machine overheated — and some are errors, like a height recorded as 1800 cm instead of 180 cm. Never delete outliers automatically. Plot or summarise the column first, then investigate the extreme values: check the original source if you can, and ask whether the value is physically possible.

For a quick check, the interquartile range (IQR) rule is a reasonable starting point: values more than 1.5 times the IQR beyond the first or third quartile are flagged as outliers. That flags candidates for investigation — it does not prove they are errors. Keep real outliers and consider transforming the column (a log transform, for example) if a few large values dominate the scale. Remove or cap only values you can show are errors, and record each removal.

5. Fix label errors

Label errors are the most damaging defect because the model learns directly from the labels. A mislabelled image, a wrong class in a spreadsheet, a sentiment label flipped by a careless annotator — each one teaches the model the wrong thing, and label errors are invisible to most automated checks. The practical defences are sampling (manually re-check a random sample of labels, especially the ones the model gets wrong during training), cross-checking labels against a rule or a second source where one exists, and looking at the confusion between specific classes — if two classes are confused far more than others, check whether their labels were swapped somewhere.

6. Remove leakage-causing columns

Leakage is information in the training data that would not be available at prediction time. Classic examples: a column that records the outcome (a "disease diagnosed" flag in a dataset meant to predict disease), an ID column that happens to correlate with the label, or a timestamp from after the event being predicted. Leakage makes accuracy look excellent and the model useless. Before training, go through every column and ask: "Would I know this value when I actually need to make the prediction?" If the answer is no, drop the column.

Split before you clean (the rule that saves your results)

This is the single most important rule in the guide, and the one students break most often: split your data into train and test sets BEFORE any cleaning step that uses statistics computed from the data.

Filling missing values with the column mean, scaling features, or choosing outlier thresholds all use statistics. If you compute those statistics on the full dataset and then split, information from the test set has leaked into the training process. Your test accuracy will look better than the model deserves, and the inflation is silent — nothing errors, nothing warns you.

The correct order is:

  1. Split into train and test (and validation, if you use one).
  2. Compute cleaning statistics (means, medians, scalers, outlier thresholds) on the TRAIN set only.
  3. Apply the same transformations to the test set using the train statistics.
  4. Never re-fit anything on the test set.

This applies to imputation, scaling, encoding rare categories, and feature selection. Steps that do not use data statistics — removing exact duplicates, fixing a date format, converting units — can be done before the split, because they cannot leak information. When in doubt, do it after the split.

A small pandas workflow

The workflow below follows the order in this guide. It is deliberately small — read it as a template to adapt, not a script to run blindly on your data. Each step prints a count so you can see what changed.

import pandas as pd

df = pd.read_csv('raw_data.csv')
print('Rows at start:', len(df))

# 1. Duplicates
before = len(df)
df = df.drop_duplicates()
print('Duplicates removed:', before - len(df))

# 2. Missing values — how bad is it?
print(df.isna().sum())

# 3. Fix a date column and a units problem
df['date'] = pd.to_datetime(df['date'], errors='coerce')
df['height_cm'] = df['height_cm'].astype(float)

# 4. Split BEFORE statistics-based cleaning
from sklearn.model_selection import train_test_split
train, test = train_test_split(df, test_size=0.2, random_state=42)

# 5. Impute with the TRAIN median, apply to both sets
median_val = train['temperature'].median()
train['temperature'] = train['temperature'].fillna(median_val)
test['temperature'] = test['temperature'].fillna(median_val)

# 6. Flag imputed rows so you can check them later
train['temperature_imputed'] = train['temperature'].isna()
test['temperature_imputed'] = test['temperature'].isna()

print('Train rows:', len(train), '| Test rows:', len(test))

Two things to notice. First, the median is computed on the train set only and then applied to both — that is the no-leakage rule in code. Second, the script prints row counts at each stage. If your row count drops sharply at any step, that is the moment to stop and investigate, not to carry on and hope.

Verifying the cleaned dataset

Cleaning is not done when the code runs without errors. Verify the result:

  • Row counts before and after. Record the starting row count, the count after each major step, and the final count. A large drop needs an explanation in your report.
  • Missing values after cleaning. Run the missing-value summary again on the cleaned data. Every remaining missing value should be a deliberate choice (a flagged column, for example), not an oversight.
  • Distribution sanity checks. Compare the mean, median, minimum and maximum of each numeric column before and after cleaning. A mean that jumps sharply after cleaning usually means you removed real data along with the errors, or that an outlier was doing more work than you realised.
  • Category counts. List the distinct values in each categorical column. Surprise values — a typo variant you missed, a category with one member — show up here.
  • A few rows by eye. Print the first ten rows and a random ten rows of the cleaned data and read them. Automated checks miss things a human spots in seconds: a date in the wrong century, a name in a numeric column, a label that contradicts the row's other values.
  • Reproducibility. Keep the raw file untouched, keep the cleaning script, and make the script runnable from raw to clean in one go. If a reviewer asks how a value was produced, you should be able to point at the exact line.

Common student mistakes

  • Cleaning on the full dataset, then splitting. This leaks test statistics into training and inflates accuracy. Split first, as above.
  • Silently dropping 40% of the rows. If a third or more of your data disappears during cleaning, the problem is the data collection, not the cleaning. Investigate the source instead of deleting the evidence.
  • Filling missing values with the mean of the test set. Same leakage problem, in a subtler form. All statistics come from the train set only.
  • Deleting every outlier. Real outliers carry information. Investigate before you delete, and cap or transform instead of deleting when the value is genuine.
  • Treating imputed values as real data. An imputed value is a guess. Flag it, and check whether your model's errors cluster on imputed rows.
  • Cleaning the labels last, or never. Label errors hurt more than any other defect. Budget time to check them.
  • No record of what changed. "I cleaned the data" is not documentation. Row counts, the reason for each removal, and the script itself are the documentation.

FAQ

Should I drop rows with missing values or fill them in?
It depends on how much is missing and why. Drop when only a few percent of rows are affected and the missingness looks random. Impute (with the train-set median or mode) when a column is mostly complete and you need the rows. Drop the column when most of it is missing. Always flag imputed values.

How much data loss during cleaning is acceptable?
There is no universal number, but losing more than about 10–15% of rows should make you stop and investigate the collection process. Losing 30–40% almost always means the dataset or the collection method needs fixing, not more aggressive cleaning.

Can I clean the data in a spreadsheet instead of code?
You can, for a small dataset, but code is better for anything you need to defend: a script records every decision, runs the same way twice, and can be re-run on new data. Spreadsheet cleaning leaves no audit trail unless you document each step manually.

What if my dataset has no missing values at all?
Be suspicious, not relieved. Check for placeholder values that stand in for missing data — 0, -1, 999, "N/A" as a string, or a future date. A dataset with no missing values often has its missingness hidden rather than absent.

Should I remove duplicates before or after the train/test split?
Before. Exact duplicates are a data-integrity fix, not a statistical one, and removing them after the split leaves the same row in both sets — the leakage problem again.

How do I handle a column with mixed types, like numbers stored as text?
Convert the column explicitly and inspect the values that fail to convert — they are usually typos, units written into the cell ("45 kg"), or placeholder text. Fix the source values where you can, and coerce the rest to missing rather than silently dropping the rows.

Limitations

This guide covers the cleaning steps that apply to tabular datasets in typical student machine learning projects. It does not cover cleaning for images (deduplication of near-identical images, corrupt file handling), text (tokenisation, encoding fixes, language detection) or audio, each of which has its own defect patterns. It also does not cover advanced imputation methods such as k-nearest-neighbour or model-based imputation, or automated data-validation frameworks — those are worth learning once the manual process in this guide is second nature. Finally, cleaning cannot rescue a dataset that was collected wrongly: if the labels are systematically wrong or the sample does not represent the problem, no amount of cleaning will fix it, and the honest conclusion is to re-collect or re-scope the project.