How to Handle Missing Data in a Machine Learning Project

Blank cells in a dataset are not a formatting problem — how you fill them changes your model's results. This guide explains MCAR, MAR and MNAR missingness, how to measure the damage, when to drop rows and when to impute, with a worked eight-student example and the train-first leakage rule.

Written by Projectech12 min readPublished
For B.E./B.Tech Computer Science, IT and AI/ML students cleaning real datasets for machine learning projects and reports Topics: Python, Pandas, Scikit-learn, Machine Learning
Technical illustration of a dataset table with highlighted blank cells being filled by imputation, shown as a clean data grid with a magnifier and chart
Illustration generated for this guide.
In this guide

Your dataset has blanks. A sensor dropped a reading, a survey respondent skipped the income question, a spreadsheet column is half empty. Your model will not accept blanks — and the way you fill them changes your results more than most students expect. A column filled with the mean looks complete, but it quietly shrinks your variance, hides the reason the data went missing, and can leak information from your test set into your training.

This guide covers the three ways data goes missing, how to measure the damage, the imputation methods that actually work, and the mistakes that turn a fixable dataset into a misleading model.

Quick answer

First measure how much is missing and in which columns, then work out why it is missing. Drop rows only when little is missing and it is missing at random. Otherwise impute: median for skewed numbers, mode for categories, interpolation for time series, and KNN or iterative imputation when the pattern is complex. Always compute imputation values on the training set only, and report what fraction of the data you filled in.

The three ways data goes missing

Statisticians classify missing data into three types, and the type decides the fix. The names matter because examiners ask about them.

Type Meaning Example
MCAR — missing completely at random The blank has nothing to do with any value, observed or missing A sensor packet is lost to radio interference
MAR — missing at random The blank depends on data you can see, but not on the missing value itself Blood pressure is missing for outpatients, because outpatients are not measured — you can see who is an outpatient
MNAR — missing not at random The blank depends on the missing value itself High earners skip the income question because their income is high

MCAR is the friendly case: dropping those rows or filling with the mean does little damage, because the remaining data still represents the whole. MAR is manageable: the pattern is visible in other columns, so a good imputation can recover it. MNAR is the dangerous one: no imputation can recover information that was never recorded, and filling it in with averages actively misleads the model. If you suspect MNAR — income, marks, anything people hide when the value is extreme — say so in your report and treat the result with caution rather than papering over it.

You cannot prove which type you have from the data alone. But you can look for clues: compare the rows with missing values against the complete rows. If the missing group differs systematically on other columns — younger, lower marks, a different sensor — it is not MCAR.

Step 1: measure how much is missing, and where

Before touching anything, quantify the problem. In pandas:

import pandas as pd

df = pd.read_csv("student_data.csv")

missing = df.isna().sum()
print(missing[missing > 0])

print((df.isna().mean() * 100).round(1))

The first block counts blanks per column; the second gives the percentage. Also check whether blanks cluster in the same rows:

print("Rows with any missing value:", df.isna().any(axis=1).sum())
print("Total rows:", len(df))

Three numbers now drive every decision: the percentage missing per column, whether the blanks sit in a few rows or spread across many, and whether the incomplete rows look different from the complete ones. A column that is 60% blank is a different problem from a column with three blanks in 1,000 rows, and treating them the same way is the most common error in student reports.

Step 2: decide per column

Situation Sensible action
Under 5% missing, MCAR Drop the rows — the loss is small and the bias is negligible
5–30% missing Impute with a method that fits the column (below)
Over 40% missing Consider dropping the column — it carries little reliable signal
Target column has blanks Drop those rows — you cannot train on a missing answer
MNAR suspected Do not impute blindly; flag it, add a missingness indicator, discuss it in the report

Dropping rows is called listwise deletion. It is honest and simple, but it has a cost: if blanks cluster in one group, deleting those rows deletes that group from your training data. Deleting 12% of rows that are mostly one class quietly changes your class balance, and the model you train no longer represents the problem you set out to solve.

Worked example: one missing mark

Eight students, study hours against exam marks. One mark is missing:

Student Study hours Marks
1 2 45
2 3 52
3 4 58
4 5 —
5 6 70
6 7 76
7 8 82
8 9 88

Three ways to fill the gap, three different answers:

  • Mean imputation. The observed marks sum to 471 across 7 students, so the mean is 471 / 7 = 67.3. Fill in 67.3. It is quick, but it ignores the fact that this student studied 5 hours — between the 4-hour student (58) and the 6-hour student (70).
  • Median imputation. The observed marks sorted are 45, 52, 58, 70, 76, 82, 88 — the median is 70. Fill in 70. For a skewed column the median is safer than the mean, but here it is worse: it claims a 5-hour student scored the same as a 6-hour one.
  • Interpolation. The marks rise steadily with hours, so the missing value should sit between 58 and 70 — about 64. A quick straight-line fit through the observed points gives roughly 63. The pattern in the data is worth more than any single statistic.

The lesson generalises: the best imputation uses the relationships in your data, not just the column's own average. Mean and median are fallbacks for columns with no useful relationships, not the default.

Imputation methods, from simple to serious

Mean and median. Fill every blank with the column's mean (symmetric data) or median (skewed data, or data with outliers). Fast and transparent. The cost: every filled value is identical, so the column's variance shrinks and correlations with other columns weaken. With 20% of a column filled this way, your model sees a column that looks more predictable than it really is.

Mode for categories. Fill a missing category with the most common value — for example, the most common department or device type. Only sensible when one category genuinely dominates. If the column is evenly split, the mode is a coin toss dressed as data.

Forward fill for time series. In sensor logs and time-ordered data, the previous reading is usually the best guess for a missing one: df["temperature"].ffill(). Use it for short gaps only — a sensor that died for a week should not be forward-filled for a week.

KNN imputation. Find the rows most similar to the incomplete row (on the columns that are present) and average their values. It uses relationships between columns, which is why it beat the mean in the worked example. In scikit-learn:

from sklearn.impute import KNNImputer

imputer = KNNImputer(n_neighbors=5)
df_filled = pd.DataFrame(
    imputer.fit_transform(df),
    columns=df.columns
)

Iterative imputation. Model each column from all the others, fill it in, then repeat — the approach behind the MICE method. It is the strongest general-purpose option when several columns have blanks at once, and it is available as IterativeImputer in scikit-learn's experimental module. It is slower and harder to explain in a report, so use it when the missingness is heavy, not for three blanks.

A category called "Missing". For categorical columns, sometimes the best fill is no fill: keep the blank as its own category. If "income not disclosed" behaves differently from any income band, the model should be allowed to learn that. This also preserves the information that the value was missing, which mean imputation destroys.

A missingness indicator. Add a binary column marking which rows were imputed — 1 where the value was filled, 0 where it was real. The model can then learn that imputed values deserve less trust. It costs one column and often improves results noticeably when the missingness itself carries signal, as in the MAR case.

The leakage rule: fit on train, apply everywhere

This is the mistake that invalidates the most student projects. If you compute the column mean on the whole dataset and then split into train and test, the training data has already "seen" the test set through that mean. The correct order is:

  1. Split into train and test first.
  2. Compute every imputation value (mean, median, KNN neighbours) on the training set only.
  3. Apply those same values to the test set.

Scikit-learn pipelines enforce this automatically:

from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier

pipe = Pipeline([
    ("imputer", SimpleImputer(strategy="median")),
    ("model", RandomForestClassifier(random_state=42)),
])
pipe.fit(X_train, y_train)

Fit the pipeline on the training data and the imputer learns the median from the training set alone. Cross-validation then re-fits the whole pipeline on each fold, so the rule holds there too. If your report's accuracy was measured with imputation fitted on the full dataset, the number is optimistic — re-run it properly before quoting it.

Comparing strategies honestly

Do not pick an imputation method by gut feel. Run the same model with two or three strategies and compare on a validation split — dropping rows, median imputation, and KNN imputation, for example. Report all three numbers, not just the best one, and note the fraction of data each strategy touched. A strategy that fills 30% of a column and gains half a percent of accuracy has bought that gain with invented data, and an examiner who asks "how much of this column did you invent?" deserves a straight answer.

Also check the effect on the model's behaviour, not just its score: does the imputed column's importance change dramatically between strategies? If it does, the model is sensitive to your choice, and that sensitivity belongs in the limitations section of your report.

Six mistakes to avoid

  1. Imputing the target column — a missing label is not data. Drop those rows.
  2. Filling blanks before splitting — leaks test information into training. Split first, always.
  3. Filling with zero without thinking — zero is a real value. A missing income is not a zero income, and a missing temperature is not freezing.
  4. Using the mean on a skewed column — income, house prices and sensor readings with outliers need the median.
  5. Forward-filling a long gap — a sensor that was dead for a week was not reading the same value for a week.
  6. Hiding the missingness — if you do not report what fraction was imputed, nobody can judge your results, including you.

Frequently asked questions

How much missing data is too much?
There is no universal threshold, but as a working rule: under 5% is trivial, 5–30% is manageable with good imputation, and above 40% in a column means the column is mostly guesswork — consider dropping it and saying why.

Should I drop rows or impute?
Drop when little is missing and it is random. Impute when dropping would delete a meaningful share of your data or a whole subgroup. When in doubt, try both and compare on a validation split.

Does imputation change my model's accuracy?
Yes, and usually upward on the training data — filled-in values make the data look cleaner than it is. Judge strategies on a held-out test set, never on the data you imputed.

What about missing values in images or text?
Different problem. A missing image is usually dropped; a missing word is handled by the tokenizer. This guide covers tabular data — the kind in CSV files that most student ML projects use.

Can I just use a model that handles missing values natively?
Some can — gradient boosting libraries such as XGBoost and LightGBM learn a default direction for missing values. That is a legitimate choice, but it is still a choice: document it, and compare against an imputation baseline so you know what it bought you.

What do I write in the report?
One short paragraph per affected column: how much was missing, why you think it was missing, what you did about it, and what fraction of the final dataset is imputed. That paragraph is often the difference between a report that looks rigorous and one that looks lucky.

Limitations

No imputation creates information — it only spreads the information you already have across the gaps, and every method makes assumptions that can be wrong. Mean imputation assumes the average is representative; KNN assumes similar rows have similar values; iterative imputation assumes the relationships between columns are stable. When data is MNAR, none of these assumptions hold, and the honest answer is to report the limitation and limit the claims, not to fill harder. The methods here also assume tabular data; time-series gaps, missing images and missing text need their own treatment. Finally, the percentages in this guide are working rules from common practice, not statistical guarantees — a 10% missing rate in a 100-row dataset is a very different problem from 10% in a 100,000-row one.

What to do next

Run the measurement snippet on your own dataset and write down the three numbers: percentage missing per column, rows affected, and whether the incomplete rows look different. Then try two strategies — dropping rows and one imputation method — and compare them on a validation split before you commit. Pair this with the train-validation-test split guide so your comparison is honest, and the cross-validation guide when a single split feels too noisy.

If you are building a machine learning project and need help with data cleaning, model selection or a complete working build, you can get a quotation on WhatsApp: https://wa.me/918275719193 — share your dataset, the problem you are solving, and your deadline.