Sign in

Missing values

Missing value handling (imputation)

Fills or removes missing entries in a numeric table, using rules learned from the training data only.

Overview

Most models cannot compute with a hole in the table, so each missing entry (NaN) must be filled or its row or column removed. Filling is called imputation. The simplest fill is one typical value per column, such as the mean or the median. A better guess looks at the rows most similar to the incomplete one and averages what they hold in that column. Every fill is a guess, so the handler learns its fill values from the training data and can add a flag column that records where a value was missing.

A short history

Statisticians long dealt with gaps by dropping incomplete cases or filling in means. Donald Rubin's 1976 paper "Inference and missing data" gave the framework still used: data may be missing completely at random, missing at random, or missing not at random, and the right treatment depends on which. Rubin later introduced multiple imputation, and his 1987 book with Roderick Little became the standard reference.

How it works

  1. Call missing_report to see how much is missing per column and how many rows are affected.
  2. Choose a strategy: mean, median, most_frequent or constant fill one value per column, knn fills from similar rows, drop_rows and drop_columns remove data.
  3. Call fit on the training table. It stores one fill value per column in statistics_, the columns to keep, and for knn a copy of the training rows.
  4. Call transform. For the simple strategies every NaN is replaced by its column's stored value.
  5. For knn, measure the distance from an incomplete row to each training row over the columns both have, take the n_neighbors nearest rows that hold the missing column, and use their mean.
  6. If add_indicator is on, append one 0 or 1 column for each column that had missing values in training.
  7. Apply the same fitted handler to the validation and test tables.

Watch out for

  • Filling with the mean leaves the mean unchanged but shrinks the variance, because every filled value sits exactly at the centre. Correlations with other columns weaken too.
  • Fitting on the full table before splitting lets test rows shape the fill values. Fit on the training split and only transform the rest.
  • If values are missing for a reason, for example high incomes left blank, any fill is biased. The missing indicator lets the model use the pattern itself.
  • The knn distance is dominated by columns with large units. Scale the columns first, or neighbours are chosen by one column alone.
  • drop_rows changes the number of rows, so the labels must be cut the same way with kept_rows or they no longer line up.

Use cases

When to use it

Whenever a numeric table has NaN entries and the model cannot handle them itself. Use the median for skewed columns, knn when columns are related, and dropping only when little is lost.

In industry

Healthcare analytics
Patient records lack lab tests that were never ordered, and models fill them with medians and add a flag, since the absence itself carries information.
Survey research
Statistical agencies impute skipped answers so that published totals are not biased toward people who answered every question.
Sensor data
Industrial systems fill short gaps from dropped readings before features are computed, and discard stretches where a sensor was offline.

Choosing it: what must hold

  • A view of how much is missing per column and whether the gaps relate to other columns or to the target.
  • Fill values learned from the training data only, then applied unchanged to validation and test data.
  • For mean or median filling, a modest share of missing entries. Filling a mostly empty column creates false certainty.
  • For nearest-neighbour filling, columns on comparable scales and a table small enough to search.

When to choose something else

IfUse instead
A column is mostly emptyDrop the column, or keep only an indicator of whether it was present
The model is a gradient boosted tree that handles missing entries itselfXGBoost, LightGBM or CatBoost with the gaps left in place
The data are a time series with short gapsForward fill or interpolation along time
You need valid uncertainty for a statistical conclusionMultiple imputation

Math foundations

  1. Mean imputation

    x^ij=xˉj=1∣Oj∣∑i∈Ojxij\hat{x}_{ij} = \bar{x}_j = \frac{1}{\lvert O_j \rvert} \sum_{i \in O_j} x_{ij}

    A missing entry in column jj is replaced by the mean over OjO_j, the rows where that column is observed. The median strategy uses the middle observed value instead, which outliers barely move.

  2. What mean filling does to the spread

    Var⁡filled=∣Oj∣n Var⁡observed\operatorname{Var}_{\text{filled}} = \frac{\lvert O_j \rvert}{n}\, \operatorname{Var}_{\text{observed}}

    The filled values add nothing to the sum of squared deviations but do add to the row count. The variance shrinks by the share of observed rows.

  3. Distance with gaps

    d(a,b)=p∣S∣∑j∈S(aj−bj)2d(a, b) = \sqrt{\frac{p}{\lvert S \rvert} \sum_{j \in S} (a_j - b_j)^2}

    Two rows are compared only on the set SS of columns both observe. The factor p/∣S∣p / \lvert S \rvert rescales the sum to all pp columns, so rows that share few columns are not judged close by default.

  4. Nearest-neighbour fill

    x^ij=1k∑r∈Nk(i, j)xrj\hat{x}_{ij} = \frac{1}{k} \sum_{r \in N_k(i,\, j)} x_{rj}

    The fill is the mean of column jj over the kk nearest training rows that observe it. If no such row exists, the template falls back to the column mean.

  5. Missing share of a column

    fj=n−∣Oj∣nf_j = \frac{n - \lvert O_j \rvert}{n}

    The fraction of column jj that is missing. drop_columns removes the column when fjf_j is above max_missing_fraction.

Symbols

xijx_{ij}
the value in row i and column j
x^ij\hat{x}_{ij}
the value filled in for a missing entry
OjO_j
the set of rows where column j is observed
xˉj\bar{x}_j
the mean of the observed values of column j
n, pn,\ p
the number of rows and the number of columns
SS
the columns observed in both rows being compared
Nk(i,j)N_k(i, j)
the k nearest training rows to row i that observe column j
kk
n_neighbors
fjf_j
the fraction of column j that is missing

Worked by hand

One column holds the values 2, 4, NaN and 6. Fill it with the mean and compare the variance before and after. Variances divide by the number of values used.

xˉ=2+4+63=4\bar{x} = \frac{2 + 4 + 6}{3} = 4
Var⁡observed=(2−4)2+(4−4)2+(6−4)23=83≈2.67\operatorname{Var}_{\text{observed}} = \frac{(2-4)^2 + (4-4)^2 + (6-4)^2}{3} = \frac{8}{3} \approx 2.67
Var⁡filled=(2−4)2+0+0+(6−4)24=84=2\operatorname{Var}_{\text{filled}} = \frac{(2-4)^2 + 0 + 0 + (6-4)^2}{4} = \frac{8}{4} = 2
28/3=34=∣O∣n\frac{2}{8/3} = \frac{3}{4} = \frac{\lvert O \rvert}{n}

The filled column is 2, 4, 4, 6. Its mean is still 4 but its variance fell from 2.67 to 2, exactly the share of observed rows.

Visual example

Loading the example.

Try this

  • With the mean strategy, every filled point sits on one flat line. Raise the missing share and watch the variance ratio follow the share of observed rows.
  • Switch to knn: the filled points now follow the slope of the data. Move n_neighbors from 1 to 15 and watch them flatten again.
  • Press a filled point to see which rows gave it its value.

Code sample

import numpy as np
from impl import MissingValueHandler, missing_report
from config import MissingValueConfig

X = np.array([[1.0, 2.0], [np.nan, 4.0], [3.0, np.nan], [5.0, 10.0]])
print(missing_report(X)["per_column"])           # [1 1]
handler = MissingValueHandler(MissingValueConfig(strategy="median")).fit(X)
X_filled = handler.transform(X)                  # NaN in column 0 becomes 3.0, in column 1 becomes 4.0
Read the implementation (132 lines)
"""Missing-value handling for numeric tables: report, impute (statistic, constant, k-NN) or drop.

NumPy only. Missing means NaN. `fit` learns what it needs from the training data (fill values, the rows used
as neighbours, the columns to keep) and `transform` applies it to any table with the same columns.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import MissingValueConfig
except ImportError:  # run from the template's own folder
    from config import MissingValueConfig


def missing_report(X) -> dict:
    """Count missing values. X: (n_samples, n_features).

    Returns {"per_column": counts (n_features,), "fraction": shares (n_features,),
    "rows_with_missing": int, "total": int}.
    """
    mask = np.isnan(np.asarray(X, dtype=float))
    return {
        "per_column": mask.sum(axis=0),
        "fraction": mask.mean(axis=0),
        "rows_with_missing": int(mask.any(axis=1).sum()),
        "total": int(mask.sum()),
    }


def _mode(column: np.ndarray) -> float:
    """Most frequent non-NaN value of a 1-D array (the smallest one on ties); NaN when all are missing."""
    values = column[~np.isnan(column)]
    if values.size == 0:
        return float("nan")
    unique, counts = np.unique(values, return_counts=True)
    return float(unique[np.argmax(counts)])


class MissingValueHandler:
    """Imputes or drops NaN values.

    After `fit`: `statistics_` (n_features,) holds the per-column fill value (column mean for "knn", used as
    a fallback), `keep_columns_` the indices of the columns kept, `indicator_columns_` the columns that get a
    missing-indicator.
    """

    def __init__(self, config: MissingValueConfig | None = None) -> None:
        self.config = config or MissingValueConfig()
        self.statistics_: np.ndarray | None = None
        self.keep_columns_: np.ndarray | None = None
        self.indicator_columns_: np.ndarray | None = None
        self._train: np.ndarray | None = None

    def fit(self, X) -> "MissingValueHandler":
        """Learn fill values (and neighbours, columns to keep) from X, shape (n_samples, n_features)."""
        X = np.asarray(X, dtype=float)
        if X.ndim != 2:
            raise ValueError("X must be 2-D: (n_samples, n_features)")
        mask = np.isnan(X)
        strategy = self.config.strategy
        with np.errstate(all="ignore"):
            if strategy == "median":
                stats = np.array([np.median(c[~np.isnan(c)]) if (~np.isnan(c)).any() else np.nan for c in X.T])
            elif strategy == "most_frequent":
                stats = np.array([_mode(c) for c in X.T])
            elif strategy == "constant":
                stats = np.full(X.shape[1], float(self.config.fill_value))
            else:  # mean; also the fallback of knn and unused by the drop strategies
                counts = (~mask).sum(axis=0)
                stats = np.where(counts > 0, np.nansum(X, axis=0) / np.maximum(counts, 1), np.nan)
        # a column with no observed value at all falls back to the constant fill value
        self.statistics_ = np.where(np.isnan(stats), float(self.config.fill_value), stats)
        if strategy == "drop_columns":
            self.keep_columns_ = np.flatnonzero(mask.mean(axis=0) <= self.config.max_missing_fraction)
        else:
            self.keep_columns_ = np.arange(X.shape[1])
        self.indicator_columns_ = np.flatnonzero(mask.any(axis=0))
        self._train = X.copy() if strategy == "knn" else None
        return self

    def _knn_fill(self, X: np.ndarray) -> np.ndarray:
        """Fill each NaN with the mean of that column over the k nearest training rows that observe it.

        The distance between two rows uses only the columns both observe, rescaled to the full column count
        (the "NaN-Euclidean" distance): sqrt(n_features / n_shared * sum of squared differences).
        """
        train, k, d = self._train, self.config.n_neighbors, X.shape[1]
        train_seen = ~np.isnan(train)
        train_zero = np.where(train_seen, train, 0.0)
        out = X.copy()
        for i in np.flatnonzero(np.isnan(X).any(axis=1)):
            seen = ~np.isnan(X[i])
            shared = train_seen & seen  # (n_train, d)
            diff = np.where(shared, train_zero - np.where(seen, X[i], 0.0), 0.0)
            n_shared = shared.sum(axis=1)
            dist = np.where(n_shared > 0, np.sqrt(d / np.maximum(n_shared, 1) * (diff**2).sum(axis=1)), np.inf)
            order = np.argsort(dist, kind="stable")
            for j in np.flatnonzero(~seen):
                donors = [r for r in order if train_seen[r, j] and np.isfinite(dist[r])][:k]
                out[i, j] = train[donors, j].mean() if donors else self.statistics_[j]
        return out

    def transform(self, X) -> np.ndarray:
        """Return X with missing values handled. "drop_rows" returns fewer rows (see `kept_rows`)."""
        if self.statistics_ is None:
            raise RuntimeError("call fit before transform")
        X = np.asarray(X, dtype=float)
        if X.ndim != 2 or X.shape[1] != self.statistics_.shape[0]:
            raise ValueError(f"X must have {self.statistics_.shape[0]} columns")
        mask = np.isnan(X)
        strategy = self.config.strategy
        if strategy == "drop_rows":
            out = X[~mask.any(axis=1)]
        elif strategy == "drop_columns":
            out = X[:, self.keep_columns_]
        elif strategy == "knn":
            out = self._knn_fill(X)
        else:
            out = np.where(mask, self.statistics_, X)
        if self.config.add_indicator and self.indicator_columns_.size:
            rows = ~mask.any(axis=1) if strategy == "drop_rows" else slice(None)
            out = np.hstack([out, mask[rows][:, self.indicator_columns_].astype(float)])
        return out

    def kept_rows(self, X) -> np.ndarray:
        """Indices of the rows of X that "drop_rows" keeps (use it to drop the same rows from the labels)."""
        return np.flatnonzero(~np.isnan(np.asarray(X, dtype=float)).any(axis=1))

    def fit_transform(self, X) -> np.ndarray:
        """Fit on X and return the handled X."""
        return self.fit(X).transform(X)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Create a table of 200 rows and 3 correlated columns, then set 20 percent of one column to NaN. Run missing_report, then fit a MissingValueHandler with strategy mean and another with strategy knn through MissingValueConfig. Compare each filled column with the true values you removed, and compare the column variance before and after filling.

Check on learning

  1. Mean imputation keeps the column mean exactly right. Why can a model trained on the filled table still be worse than one trained on only the complete rows?
    A way to think about it

    Look at what happens to the variance of the column and to its relation with other columns when many values sit at one point.

  2. In a survey, people with high incomes skip the income question more often. What does median imputation do to the income column, and how could add_indicator help?
    A way to think about it

    Compare the typical income of people who answered with that of people who did not. Then ask what a 0 or 1 flag lets a model learn.

  3. Why must the fill values come from the training split, even though using the whole table would give a slightly better estimate of the mean?
    A way to think about it

    Think about what the test set is for. Any number computed from test rows and used in training is a small view of the answer sheet.

  4. Two rows share only one observed column and agree on it. The gap-aware distance between them is zero. Is that a trustworthy sign that the rows are similar?
    A way to think about it

    The rescaling fixes the size of the distance, not its reliability. Consider how much evidence one shared column gives.