Reading history

Handling Missing Data in Python: SimpleImputer and KNNImputer

5 min read 1 views

Learn to handle missing data in Python: count gaps with pandas, fill them with SimpleImputer and KNNImputer, and add missing-value indicators.

Real datasets have holes: a customer skipped the age field, a sensor went offline, a form was half filled in. Most scikit-learn models refuse to train on missing values, so you must decide what to do with them. This lesson shows how to measure missing data, fill it in (imputation) with SimpleImputer and KNNImputer, and keep the fact that a value was missing as a useful signal.

In this lesson you will learn

  • Counting missing values with pandas
  • Mean, median and most-frequent imputation
  • Filling gaps from similar rows with KNNImputer
  • Why a “was missing” flag can boost accuracy
  • When to drop rows or columns instead

You should know data preprocessing and pipelines.

Finding and Filling Gaps

import numpy as np
import pandas as pd
from sklearn.impute import KNNImputer, SimpleImputer

df = pd.DataFrame({
    "age":    [25, 32, np.nan, 41, 29, np.nan],
    "income": [30, 48, 52, np.nan, 35, 61],
    "city":   ["Dhaka", "Sylhet", np.nan, "Dhaka", "Dhaka", "Khulna"],
})
print("Missing per column:")
print(df.isna().sum())

num = df[["age", "income"]]
print("\nMedian fill:")
print(SimpleImputer(strategy="median").fit_transform(num))
print("\nKNN fill (2 nearest rows):")
print(KNNImputer(n_neighbors=2).fit_transform(num))
print("\nMost frequent city:",
      SimpleImputer(strategy="most_frequent").fit_transform(df[["city"]]).ravel())

Output

Missing per column:
age       2
income    1
city      1
dtype: int64

Median fill:
[[25.  30. ]
 [32.  48. ]
 [30.5 52. ]
 [41.  48. ]
 [29.  35. ]
 [30.5 61. ]]

KNN fill (2 nearest rows):
[[25.  30. ]
 [32.  48. ]
 [30.5 52. ]
 [41.  41.5]
 [29.  35. ]
 [30.5 61. ]]

Most frequent city: ['Dhaka' 'Sylhet' 'Dhaka' 'Dhaka' 'Dhaka' 'Khulna']
  • df.isna().sum() counts the missing values in each column. Always start here.
  • SimpleImputer(strategy="median") fills each gap with the column’s median: 30.5 for age and 48 for income. The median ignores extreme values, which makes it safer than the mean for skewed columns like income.
  • KNNImputer(n_neighbors=2) finds the two rows most similar on the columns that are present and averages their values. The 41-year-old gets income 41.5, the average of the two closest ages (32 and 29), instead of the overall median.
  • For text columns, use strategy="most_frequent". The missing city becomes “Dhaka”, the most common value.

When Missing Means Something

Sometimes the gap itself tells a story. People with high debts may skip the debt question; a meter may fail more often in a faulty building. Filling the value hides that. add_indicator=True adds a 0/1 column saying “this value was missing”.

import numpy as np
from sklearn.datasets import make_classification
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = make_classification(n_samples=1500, n_features=6, n_informative=4, random_state=2)
rng = np.random.default_rng(2)
# Values in column 0 go missing far more often for class 1: the gap itself is informative
missing = rng.random(len(y)) < np.where(y == 1, 0.5, 0.05)
X[missing, 0] = np.nan
print("Share missing in column 0:", round(np.isnan(X[:, 0]).mean(), 3))

for flag in [False, True]:
    pipe = make_pipeline(SimpleImputer(strategy="mean", add_indicator=flag),
                         StandardScaler(), LogisticRegression(max_iter=1000))
    acc = cross_val_score(pipe, X, y, cv=5).mean()
    print(f"add_indicator={flag!s:<5} accuracy {acc:.3f}")

Output

Share missing in column 0: 0.267
add_indicator=False accuracy 0.835
add_indicator=True  accuracy 0.869
  • In this data, column 0 is missing for about half of class 1 rows but only 5% of class 0 rows.
  • Mean imputation alone gives 83.5% accuracy. Adding the indicator lets the model use the pattern and lifts it to 86.9%.
  • The imputer sits inside the pipeline, so cross-validation computes the fill values from the training folds only.

Choosing a Strategy

ApproachUse whenWatch out for
Drop rows (dropna())Very few rows are affected, at randomLosing data and biasing the sample
Drop the columnMost of the column is emptyThrowing away a useful signal
Median / meanNumeric columns, a quick baselineShrinks the spread of the column
Most frequent / constantText categories“missing” as its own category can be better
KNNImputerColumns related to each otherSlower; needs scaled features
add_indicator=TrueMissingness may relate to the targetAdds extra columns

Some models handle gaps on their own. HistGradientBoostingClassifier and HistGradientBoostingRegressor accept NaN directly and learn which side of each split missing values should go.

Common Mistakes

  1. Imputing before splitting, so the fill values are computed using test rows. Put the imputer in a pipeline.
  2. Filling with 0 without thinking. An age of 0 is a real value and misleads the model.
  3. Using KNNImputer on unscaled data, so the column with the largest numbers decides who the neighbours are.
  4. Forgetting that missing data may be coded differently, such as −1, 999 or an empty string. Convert these to NaN first.

Practice Exercises

Exercise 1. In a column, missing ages were stored as −1. Convert them to NaN and count them.

Show answer
df["age"] = df["age"].replace(-1, np.nan)
print(df["age"].isna().sum())

Exercise 2. Fill the missing city with the word “Unknown” instead of the most common city.

Show answer
imp = SimpleImputer(strategy="constant", fill_value="Unknown")
print(imp.fit_transform(df[["city"]]).ravel())

A separate “Unknown” category keeps missing rows apart from real Dhaka rows, which is often more honest.

Frequently Asked Questions

How much missing data is too much?

There is no fixed limit. If a column is mostly empty, the filled values are mostly guesses, so dropping it or keeping only an indicator is often better. Test both options with cross-validation.

What is IterativeImputer?

It predicts each column with missing values from the other columns, in rounds. It can be more accurate than KNN, but it is still marked experimental in scikit-learn and needs from sklearn.experimental import enable_iterative_imputer first.

Summary

  • Count gaps with isna().sum() before choosing a strategy.
  • Median and most-frequent fills are quick, safe baselines.
  • KNNImputer fills from similar rows; scale features first.
  • add_indicator=True keeps “was missing” as a feature.
  • Always impute inside a pipeline.

Next: ML Project: Customer Churn Prediction.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *