Fill missing values from the k nearest rows (KNN imputation)

Why it matters KNN imputation keeps relationships between columns, so it often beats a plain median on sensor, survey and medical tables where columns move together.

KNN imputation fills a gap with the average of that feature over the most similar rows, where similarity only uses features both rows actually have.

Write knn_impute(X, k). X is a 2D float array with np.nan for missing values. Return a filled copy. For every row i with missing features, compute its distance to every other row j as sqrt(d / c * sum of squared differences over the c coordinates present in both rows), where d is the number of columns; if c is 0 the distance is infinite. For each missing feature f of row i, the donors are the k closest rows j != i that have feature f present and a finite distance (break distance ties by smaller row index). Fill with the mean of the donors' values of f. If there are no donors, use the column mean over present values. Always use the original values of X, never values you filled earlier.

Signaturedef knn_impute(X, k)

Example

X [[1, 2, nan], [1, 2, 3], [2, 2, 5], [8, 9, 7]], k 2 gives [[1, 2, 4], [1, 2, 3], [2, 2, 5], [8, 9, 7]].

Understand the idea

KNN imputation asks: which rows look most like this one, and what value did they have here? It is like guessing a missing exam mark from the marks of the students whose other subjects match yours best.

Worked example: row [1, 2, ?] compares only the first two columns. Row [1, 2, 3] differs by 0, so the distance is 0. Row [2, 2, 5] differs by 1 in one column: sqrt(3 / 2 * 1) = 1.22. Row [8, 9, 7] is far: sqrt(1.5 * 98) = 12.1. With k = 2 the donors are the first two rows, so the gap becomes (3 + 5) / 2 = 4.

Rule: dist(i, j) = sqrt(d / c * sum over shared coordinates of (x_i - x_j)^2), then fill = mean of feature f over the k nearest rows that have f.

The d / c factor rescales a distance computed on c columns up to the full d columns. Common NaN-aware Euclidean distances work exactly this way, and KNN imputers are used on lab results and sensor logs.

Shapes and data flow

X (n, d) -> dist (n,) per incomplete row -> filled X (n, d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleknn_impute([[1, 2, np.nan], [1, 2, 3], [2, 2, 5], [8, 9, 7]], 2)
  • Sample 2: neighbour also missingknn_impute([[0, np.nan], [0.1, np.nan], [5, 10], [6, 20]], 1)