4 · Data Cleaning & Missing Data · Missing Data: Advanced Imputation

KNN imputation

KNN imputation replaces a missing feature using values from nearby observations, where “nearby” is computed from the other available features. It can preserve local nonlinear structure better than a global mean, but distance quality depends heavily on scale and irrelevant features.

Reference lessonPython exampleVisual explanation
Intuition first

What this concept means in practice

KNN imputation replaces a missing feature using values from nearby observations, where “nearby” is computed from the other available features. It can preserve local nonlinear structure better than a global mean, but distance quality depends heavily on scale and irrelevant features.

The practical value of KNN imputation comes from understanding both the transformation and the boundary around it: what information is allowed to enter, what assumption is being made, and how you know the result is still valid after the transformation.

A beginner-friendly way to reason about it is to start with a tiny case where the correct result can be checked independently. Once the mechanism is clear, scale the exact same reasoning to larger tables, pipelines or models.

PurposeUse for modest-sized numeric datasets when local similarity is meaningful.
MechanismFor each incomplete row, find neighbouring rows using features available for both records, then aggregate the neighbours’ observed values for the missing feature.
EvidenceInspect intermediate and final output; compare with an independent expectation.
Main cautionScale-sensitive distances, high dimensionality and many missing features can make neighbours unreliable.
Mechanism

Trace the operation from input to decision

For each incomplete row, find neighbouring rows using features available for both records, then aggregate the neighbours’ observed values for the missing feature.

1Input→
2Apply rule→
3Inspect state→
4Validate→
5Use result
Key rule
Imputation should be fitted inside each training split, never on the full dataset.
Visual explanation

Make the structure visible

The interactive view uses a concept-specific plot when the topic maps naturally to one; otherwise it uses a workflow view instead of leaving a broken placeholder.

Loading visual…
Practical example

Where you would use it

Estimate a missing blood-pressure value from patients with similar age, BMI and heart rate.

Use when
Use for modest-sized numeric datasets when local similarity is meaningful.
Pitfall

What can make the result misleading

Watch out
Scale-sensitive distances, high dimensionality and many missing features can make neighbours unreliable.

A useful diagnostic question is: Could the same code still run successfully if the analytical assumption were wrong? If yes, add an explicit validation check rather than relying on execution success.

Implementation

Miniature Python example

Keep the example small enough that you can inspect each stage manually.

Python
# Purpose: demonstrate KNN imputation with a small, inspectable example.
# Follow the comments and printed stages to connect each operation with its result.
# Import the library or helper used in this example.
# Step 1 — Import the module so its functions/classes are available to the rest of this example.
import numpy as np
# Import the library or helper used in this example.
# Step 2 — Import the module so its functions/classes are available to the rest of this example.
import pandas as pd
# Import the library or helper used in this example.
# Step 3 — Import only the named objects needed by the following steps, keeping dependencies explicit.
from sklearn.impute import KNNImputer

# Create a small labelled dataset that is easy to inspect by eye.
# Step 4 — Construct `X` as a tabular object with named columns for inspectable analysis.
X = pd.DataFrame({
    "age": [22, 25, np.nan, 31, 35, 38, 41, np.nan, 48, 52, 56, 60],
    "bmi": [21.1, 22.5, 24.0, np.nan, 25.2, 26.3, 27.1, 28.0, np.nan, 29.4, 30.1, 31.0],
    "score": [62, 65, 67, 70, np.nan, 73, 75, 77, 79, np.nan, 84, 86]
})
# Print this intermediate result so you can verify the workflow step by step.
# Step 5 — Display the current value explicitly so the result/state can be inspected during execution.
print("STEP 1 · Raw data shape:", X.shape)
# Print this intermediate result so you can verify the workflow step by step.
# Step 6 — Display the current value explicitly so the result/state can be inspected during execution.
print("STEP 1 · Missing counts:", X.isna().sum().to_dict())

# Store this intermediate value with a descriptive name for the next step.
# Step 7 — Compute the right-hand expression and store its result in `imputer` for the next step.
imputer = KNNImputer(n_neighbors=3)
# Create a small labelled dataset that is easy to inspect by eye.
# Step 8 — Fit the transformation on the training input and immediately transform that same input.
Xi = pd.DataFrame(imputer.fit_transform(X), columns=X.columns)
# Print this intermediate result so you can verify the workflow step by step.
# Step 9 — Display the current value explicitly so the result/state can be inspected during execution.
print("STEP 2 · Missing after KNN:", int(Xi.isna().sum().sum()))
# Print this intermediate result so you can verify the workflow step by step.
# Step 10 — Display the current value explicitly so the result/state can be inspected during execution.
print("STEP 3 · Imputed rows:")
# Print this intermediate result so you can verify the workflow step by step.
# Step 11 — Display the current value explicitly so the result/state can be inspected during execution.
print(Xi.loc[[2,3,4,7,8,9]].round(2).to_string(index=False))
Expected / illustrative output
STEP 1 · Raw data shape: (12, 3)
STEP 1 · Missing counts: {'age': 2, 'bmi': 2, 'score': 2}
STEP 2 · Missing after KNN: 0
STEP 3 · Imputed rows:
  age   bmi  score
30.33 24.00  67.00
31.00 25.17  70.00
35.00 25.20  72.33
47.00 28.00  77.00
48.00 28.17  79.00
52.00 29.40  80.00
Implementation checklist

Before you move on

  • Can you state what data or object enters the operation?
  • Can you explain what changes and what must remain invariant?
  • Have you checked the result on a tiny case you can verify independently?
  • Have you considered the main failure mode described above?
  • Can the operation be reproduced from code/formulas and documented assumptions?