Sign in

Cleaning

Data cleaning: missing values, outliers and duplicates

A cleaner that fills missing values, tames outliers and removes repeated rows in a numeric table, using numbers learned from the training data.

Overview

Raw tables have holes, typing mistakes and rows that were exported twice. A model cannot read a hole, and one wild value can pull a fitted line far from the bulk of the data. Cleaning replaces each hole with a typical value for its column, pulls or removes values that sit far outside the usual range, and keeps only the first copy of repeated rows. The typical values and the allowed range are learned once, from the training rows, and then reused unchanged on every later table.

A short history

Data cleaning grew out of statistics and database practice, with no single inventor. Donald Rubin's 1976 paper on inference with missing data gave imputation a formal footing, and John Tukey's 1977 book Exploratory Data Analysis introduced the quartile fences still used to flag outliers. Removing repeated records comes from record linkage and data warehousing work. In machine learning the key addition was to learn fill values and bounds on training data only.

How it works

  1. In fit, look at each column and ignore its missing entries (NaN, the float marker for a missing number).
  2. Learn one fill value per column: the mean, the median, the most frequent value, or a constant.
  3. Learn one lower and one upper bound per column, either Tukey's fences from the quartiles or a band around the mean measured in standard deviations.
  4. In transform, first replace every NaN with the fill value of its column.
  5. Then compare every value with the bounds. With outlier_action set to clip the value is moved onto the bound, with drop the whole row is removed.
  6. Last, drop any row that is equal to an earlier row. kept_rows_ lists the surviving input rows and report_ counts each kind of change.

Watch out for

  • Fitting on all the data lets validation rows shape the fill values and bounds, so the validation score looks better than it should.
  • The z-score band uses the mean and standard deviation, and one huge value inflates both, so the band can grow wide enough to hide the very outlier it should catch.
  • Filling many holes with one value piles rows onto that value, which shrinks the column's spread and weakens its relation to other columns.
  • Duplicate removal compares rows exactly, so two rows that differ in the last decimal are both kept, and two real, distinct events with equal values are merged into one.
  • With impute_strategy set to none the NaN values stay, and a NaN is never counted as an outlier because every comparison with it is false.

Use cases

When to use it

As the first step after loading raw numeric data and before scaling or modelling. Fit it on the training split only and apply the fitted cleaner to validation and serving data.

In industry

Healthcare analytics
Patient records arrive with missing lab values. A hospital analytics team fills them with the training median before fitting a readmission risk model.
Industrial sensors
Sensor feeds from machines contain spikes from faulty readings. Clipping values to learned bounds keeps one bad reading from dominating a predictive maintenance model.
Retail and e-commerce
Order exports often contain the same row twice after a retried upload. Removing repeated rows stops the model from counting one sale as two.

Choosing it: what must hold

  • A numeric table where missing entries are marked as NaN and not hidden behind a code such as 0 or 999.
  • A training split made before fitting, so fill values and bounds are learned from training rows only.
  • Outliers that are errors or noise. If the extreme values are the signal, as in fraud, do not clip them.

When to choose something else

IfUse instead
The model handles missing values nativelyA gradient boosted tree model such as XGBoost or LightGBM, with the missing values left in place
The columns are categories or text, not numbersThe encoding lesson, with a separate category for missing
The problem is a broken feed, such as a renamed column or a half-empty fileSchema-first data validation, which rejects the batch instead of repairing it

Math foundations

  1. Imputation

    x~ij={xijif xij is observedmjif xij is missing\tilde{x}_{ij} = \begin{cases} x_{ij} & \text{if } x_{ij} \text{ is observed} \\ m_j & \text{if } x_{ij} \text{ is missing} \end{cases}

    Each missing entry of column jj is replaced by the fill value mjm_j learned in fit. With the median, mjm_j is the middle of the observed values, which outliers barely move.

  2. Interquartile range

    IQRj=Q3,j−Q1,j\mathrm{IQR}_j = Q_{3,j} - Q_{1,j}

    The width of the middle half of the column. Q1Q_1 is the value a quarter of the data lies below and Q3Q_3 the value three quarters lie below.

  3. Tukey's fences

    Lj=Q1,j−t IQRj,Uj=Q3,j+t IQRjL_j = Q_{1,j} - t\,\mathrm{IQR}_j, \qquad U_j = Q_{3,j} + t\,\mathrm{IQR}_j

    The allowed range for outlier_method iqr. The usual choice is t=1.5t = 1.5. Because quartiles ignore the extremes, the fences stay put when a wild value appears.

  4. The z-score band

    Lj=μj−t σj,Uj=μj+t σjL_j = \mu_j - t\,\sigma_j, \qquad U_j = \mu_j + t\,\sigma_j

    The allowed range for outlier_method zscore, usually with t=3t = 3. Here σj\sigma_j is the population standard deviation of the observed values (it divides by the count, not the count minus one).

  5. Clipping

    clip⁡(x)=min⁡(max⁡(x, Lj),  Uj)\operatorname{clip}(x) = \min\big(\max(x,\, L_j),\; U_j\big)

    With outlier_action clip a value outside the range is moved onto the nearest bound, so the row is kept. With drop the row is removed instead.

Symbols

xijx_{ij}
value in row i, column j
x~ij\tilde{x}_{ij}
the same entry after imputation
mjm_j
fill value of column j learned in fit
Q1,j, Q3,jQ_{1,j},\, Q_{3,j}
first and third quartile of column j
IQRj\mathrm{IQR}_j
interquartile range of column j
tt
outlier_threshold, the width multiplier
Lj, UjL_j,\, U_j
lower and upper bound of column j
μj, σj\mu_j,\, \sigma_j
mean and population standard deviation of column j

Worked by hand

A column holds 1, 2, 2, 3 and 100. Find Tukey's fences with t=1.5t = 1.5 and clip. Sorted, the quartiles fall exactly on the second and fourth values.

Q1=2,Q3=3,IQR=3−2=1Q_1 = 2, \qquad Q_3 = 3, \qquad \mathrm{IQR} = 3 - 2 = 1
L=2−1.5×1=0.5,U=3+1.5×1=4.5L = 2 - 1.5 \times 1 = 0.5, \qquad U = 3 + 1.5 \times 1 = 4.5
clip⁡(100)=min⁡(max⁡(100, 0.5), 4.5)=4.5\operatorname{clip}(100) = \min(\max(100,\, 0.5),\, 4.5) = 4.5

The value 100 lies above the upper fence 4.5 and is moved onto it. The other four values are inside the fences and stay as they are.

Visual example

Loading the example.

Try this

  • Switch outlier_method to zscore and set t to 3: the two wild values in column 0 widen the band so far that neither is caught.
  • Click each stage in turn and watch the table change one step at a time.
  • Set outlier_action to drop and see how many rows the last stage still has to remove.

Code sample

import numpy as np
from impl import Cleaner
from config import CleaningConfig

X = np.array([[1.0, 10.0], [2.0, np.nan], [3.0, 12.0], [2.0, 11.0], [100.0, 11.0]])
cleaner = Cleaner(CleaningConfig(impute_strategy="median", outlier_action="drop"))
clean = cleaner.fit_transform(X)     # NaN -> 11.0, the row with 100.0 is dropped, then the repeated [2, 11] row
print(clean, cleaner.kept_rows_, cleaner.report_)
Read the implementation (122 lines)
"""Data cleaning for a numeric table: fill missing values, handle outliers, drop duplicate rows.

NumPy only. The table is a float array of shape (n_rows, n_columns) where NaN marks a missing value.
`fit` learns the fill values and the outlier bounds from training data; `transform` applies them, so the
same numbers are used on training, validation and serving data.
"""
from __future__ import annotations

import numpy as np

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


def _as_table(X) -> np.ndarray:
    """Return X as a float array of shape (n_rows, n_columns). A 1-D input becomes one column."""
    X = np.array(X, dtype=float)
    if X.ndim == 1:
        X = X[:, None]
    if X.ndim != 2:
        raise ValueError(f"expected a 2-D table, got shape {X.shape}")
    return X


def _most_frequent(column: np.ndarray) -> float:
    """Most common value of a 1-D array without NaN. Ties go to the smallest value."""
    values, counts = np.unique(column, return_counts=True)
    return float(values[np.argmax(counts)])


class Cleaner:
    """Impute, handle outliers, drop duplicates. Steps run in that order.

    After `fit`:
        fill_values_  shape (n_columns,), the value written into missing cells
        lower_, upper_  shape (n_columns,), the outlier bounds (-inf / +inf when the step is off)
    After `transform`:
        kept_rows_  indices of the input rows that survived, in order
        report_     counts of what was changed
    """

    def __init__(self, config: CleaningConfig | None = None) -> None:
        self.config = config or CleaningConfig()
        self.fill_values_: np.ndarray | None = None
        self.lower_: np.ndarray | None = None
        self.upper_: np.ndarray | None = None
        self.kept_rows_: np.ndarray | None = None
        self.report_: dict = {}

    def fit(self, X) -> "Cleaner":
        """Learn fill values and outlier bounds from X, shape (n_rows, n_columns), NaN = missing."""
        X = _as_table(X)
        cfg = self.config
        n_cols = X.shape[1]
        fill = np.full(n_cols, float(cfg.fill_value))
        lower = np.full(n_cols, -np.inf)
        upper = np.full(n_cols, np.inf)
        for j in range(n_cols):
            present = X[:, j][~np.isnan(X[:, j])]
            if present.size == 0:
                continue  # nothing to learn from: keep fill_value and open bounds
            if cfg.impute_strategy == "mean":
                fill[j] = present.mean()
            elif cfg.impute_strategy == "median":
                fill[j] = np.median(present)
            elif cfg.impute_strategy == "most_frequent":
                fill[j] = _most_frequent(present)
            if cfg.outlier_method == "iqr":
                q1, q3 = np.percentile(present, [25.0, 75.0])
                spread = cfg.outlier_threshold * (q3 - q1)
                lower[j], upper[j] = q1 - spread, q3 + spread
            elif cfg.outlier_method == "zscore":
                spread = cfg.outlier_threshold * present.std()
                lower[j], upper[j] = present.mean() - spread, present.mean() + spread
        self.fill_values_, self.lower_, self.upper_ = fill, lower, upper
        return self

    def transform(self, X) -> np.ndarray:
        """Clean X, shape (n_rows, n_columns). Returns shape (n_kept_rows, n_columns)."""
        if self.fill_values_ is None:
            raise RuntimeError("call fit before transform")
        X = _as_table(X)
        if X.shape[1] != self.fill_values_.shape[0]:
            raise ValueError(f"fitted on {self.fill_values_.shape[0]} columns, got {X.shape[1]}")
        cfg = self.config
        keep = np.ones(X.shape[0], dtype=bool)
        report = {"imputed": 0, "clipped": 0, "outlier_rows_dropped": 0, "duplicate_rows_dropped": 0}

        missing = np.isnan(X)
        if cfg.impute_strategy != "none":
            report["imputed"] = int(missing.sum())
            X = np.where(missing, self.fill_values_, X)

        if cfg.outlier_method != "none":
            outside = (X < self.lower_) | (X > self.upper_)  # NaN compares False, so it is never an outlier
            if cfg.outlier_action == "clip":
                report["clipped"] = int(outside.sum())
                X = np.where(outside, np.clip(X, self.lower_, self.upper_), X)
            else:
                bad_rows = outside.any(axis=1)
                report["outlier_rows_dropped"] = int(bad_rows.sum())
                keep &= ~bad_rows

        if cfg.drop_duplicates:
            seen: set[bytes] = set()
            for i in np.flatnonzero(keep):
                key = (X[i] + 0.0).tobytes()  # adding 0.0 turns -0.0 into 0.0 so the two compare equal
                if key in seen:
                    keep[i] = False
                    report["duplicate_rows_dropped"] += 1
                else:
                    seen.add(key)

        self.kept_rows_ = np.flatnonzero(keep)
        self.report_ = report
        return X[keep]

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

Practice

Build X with one column holding 1, 2, 2, 3 and 100. Fit Cleaner(CleaningConfig(outlier_method="iqr")) and then Cleaner(CleaningConfig(outlier_method="zscore", outlier_threshold=3.0)). Print lower_, upper_ and report_ after transform for both, and explain why only one of them touches the 100.

Check on learning

  1. In the column 1, 2, 2, 3, 100 the z-score band with t=3t = 3 does not flag 100, but the IQR fences do. Why does the outlier escape the rule that was meant to catch it?
    A way to think about it

    Compute the mean and standard deviation with and without the 100. Ask which statistics the outlier itself is allowed to move, and which it cannot.

  2. Why does the cleaner impute before it handles outliers and remove duplicates last? What could change if duplicates were removed first?
    A way to think about it

    Think of two rows that differ only because one has a hole or a wild value. Decide whether they should count as the same row before or after they are repaired.

  3. A column is missing in 40 percent of the rows and you fill it with the median. What happens to the column's variance and to its correlation with the label?
    A way to think about it

    Picture the histogram after filling: a tall spike at one value. Then ask what a model can learn from rows that all carry the same filled number.

  4. When would you choose outlier_action drop over clip, and what does each choice assume about why the value is extreme?
    A way to think about it

    A sensor that saturates and a row whose units are wrong are different failures. One leaves the rest of the row trustworthy, the other does not.

  5. At serving time a new row arrives with a value far above the training upper bound. The fitted cleaner clips it. Is that the behaviour you want, and how would you find out that it is happening?
    A way to think about it

    Compare what the model saw in training with what it now sees. Then look at what report_ counts and think about what a rising count over time would tell you.