TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Deleting, Mean, Median, Mode and Constant Imputation

Deleting, Mean, Median, Mode and Constant Imputation

Most scikit-learn models refuse NaN. You can make the holes go away in eight ways, and this section teaches all of them. This lesson covers the first five, the simple ones: delete rows or columns, fill numbers with the mean or the median, fill categories with the mode, or fill with a constant such as "Unknown". The next two lessons add missing-value indicators and KNN and iterative imputation.

Before choosing, look back at why the values are missing (Missing-Value Analysis): MCAR, MAR or MNAR. The mechanism decides which methods are safe. For the basics of dropna and fillna, see Handling Missing Data.

The five simple methods

# Method For Good when Bad when
1 Delete rows / columns anything few rows affected and MCAR; or a column that is mostly empty and unimportant many rows lost, or missingness depends on the label (biased sample)
2 Mean numbers roughly symmetric distribution skewed data or outliers pull the mean
3 Median numbers skewed data, outliers many identical fills create a spike
4 Mode (most frequent) categories, small integer counts one category clearly dominates it hides missingness inside the biggest class
5 Constant categories ("Unknown"), some numbers missing has its own meaning the constant is a valid value (0!)

All of them, except deleting, compute or use a single value per column. When that value is learned from data (a mean, a median, a mode), it must be learned from the training data only and then reused unchanged on validation, test and production data.

From scratch: fit on train, apply everywhere

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
income = np.round(rng.lognormal(10.5, 0.6, 12), -2)       # right-skewed
income[[2, 5, 9]] = np.nan
train, test = income[:8], income[8:]

class MedianImputer:
    def fit(self, x):
        self.value_ = np.nanmedian(x)          # learned from training data only
        return self
    def transform(self, x):
        return np.where(np.isnan(x), self.value_, x)

imp = MedianImputer().fit(train)
print("train values:", train.tolist())
print("mean of train:   ", round(float(np.nanmean(train))))
print("median of train: ", imp.value_)
print("test before:", test.tolist())
print("test after: ", imp.transform(test).tolist())
train values: [39200.0, 33500.0, nan, 38700.0, 26300.0, nan, 79400.0, 64100.0]
mean of train:    46867
median of train:  38950.0
test before: [23800.0, nan, 25000.0, 37200.0]
test after:  [23800.0, 38950.0, 25000.0, 37200.0]

The training incomes are skewed: the mean (46,867) sits well above the median (38,950) because of a few large values, so the median is the more typical fill. The test row with a missing income gets the training median. Had we recomputed the median on the test part (or on all twelve rows), information about the test data would have shaped the preprocessing, and the evaluation would no longer measure performance on unseen data.

Don't fill with zero

fillna(0) is the most common imputation bug. Zero is a real value in many columns: zero purchases last month, zero minutes of exercise, 0 °C, a balance of 0. Filling unknowns with zero merges "unknown" into a meaningful group and distorts every statistic:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(3)
n = 1000
minutes = rng.gamma(2.0, 15.0, n).round()            # exercise minutes per day
minutes[rng.random(n) < 0.15] = 0                     # people who really did not exercise
known_zero = int((minutes == 0).sum())
missing = rng.random(n) < 0.25                        # tracker not worn
recorded = pd.Series(np.where(missing, np.nan, minutes))

for name, filled in {"fill 0": recorded.fillna(0),
                     "fill median": recorded.fillna(recorded.median()),
                     "true values": pd.Series(minutes)}.items():
    print(f"{name:12s} mean {filled.mean():5.1f}   share of zeros {(filled == 0).mean():.2f}")
print("real zeros:", known_zero, " missing values:", int(missing.sum()))
fill 0       mean  19.9   share of zeros 0.38
fill median  mean  25.7   share of zeros 0.13
true values  mean  26.4   share of zeros 0.17
real zeros: 168  missing values: 251

The true share of people with zero minutes is 0.17. Filling the unknowns with 0 more than doubles it to 0.38 and drags the mean from 26.4 to 19.9 minutes: a model now learns that many people never exercise, when in fact their tracker was off. The median fill keeps the mean close (25.7) and the zero share near the truth (0.13; it is a little low because the real zeros among the missing rows now get the median). It adds its own spike at the median instead, which is why the indicator is usually added as well. If a constant fill is truly needed for numbers, pick one outside the valid range (for example -1 for a count) and add an indicator, so a model can tell it apart.

In scikit-learn: SimpleImputer inside a pipeline

SimpleImputer implements methods 2 to 5 with strategy="mean" | "median" | "most_frequent" | "constant". Put it in a ColumnTransformer so each column type gets its own strategy, and in a Pipeline so cross-validation fits it on each training fold only:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
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 OneHotEncoder, StandardScaler

rng = np.random.default_rng(1)
n = 600
df = pd.DataFrame({
    "income": rng.lognormal(10.5, 0.6, n),
    "age": rng.integers(18, 80, n).astype(float),
    "region": rng.choice(["north", "south", "east"], n, p=[0.5, 0.3, 0.2]),
})
logit = 1.2 * (np.log(df["income"]) - 10.5) - 0.03 * (df["age"] - 50) + (df["region"] == "east")
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
for col, share in [("income", 0.2), ("age", 0.1), ("region", 0.15)]:
    df.loc[rng.random(n) < share, col] = np.nan

def model(num_strategy):
    pre = ColumnTransformer([
        ("num", make_pipeline(SimpleImputer(strategy=num_strategy, fill_value=0), StandardScaler()),
         ["income", "age"]),
        ("cat", make_pipeline(SimpleImputer(strategy="constant", fill_value="Unknown"),
                              OneHotEncoder(handle_unknown="ignore")), ["region"]),
    ])
    return make_pipeline(pre, LogisticRegression())

for strategy in ["mean", "median", "constant"]:
    scores = cross_val_score(model(strategy), df, y, cv=5, scoring="roc_auc")
    label = "constant 0" if strategy == "constant" else strategy
    print(f"{label:10s} ROC AUC {scores.mean():.3f} +- {scores.std():.3f}")

complete = df.notna().all(axis=1)
print("rows left after deleting incomplete rows:", int(complete.sum()), "of", n)
fitted = model("median").fit(df, y)
num_imp = fitted[0].named_transformers_["num"][0]
print("medians learned on all rows:", [round(v) for v in num_imp.statistics_])
mean       ROC AUC 0.745 +- 0.032
median     ROC AUC 0.746 +- 0.036
constant 0 ROC AUC 0.689 +- 0.023
rows left after deleting incomplete rows: 357 of 600
medians learned on all rows: [36476, 52]

Measured with 5-fold cross-validation (ROC AUC, 600 rows), mean and median imputation score about the same here, and filling income with zero is clearly worse (0.689 against 0.745 and 0.746), because an income of 0 is an extreme value on the scale of this column. Deleting incomplete rows would have thrown away 243 of 600 rows (357 complete rows remain). Note that inside cross_val_score each fold fits its own imputer; the medians printed at the end come from a final fit on all rows, as you would do once the evaluation is finished, before deploying.

Note: region uses method 5, a constant "Unknown" category. For categories this is often better than the mode: it keeps "unknown" separate instead of adding it to north, and the one-hot encoder gives it its own column.

Pitfalls

  • Imputing before the split (or with df.fillna(df.median()) on all rows): the fill values carry information from the test rows. Use a fitted imputer inside a pipeline.
  • Deleting rows when missingness relates to the label: the remaining data no longer represents the population, and the model never sees the hard cases.
  • Imputing the target: rows with a missing label are not training data. Remove them (or use them in semi-supervised learning), never fill the label with a mean.
  • One strategy for every column: choose per column, based on type, distribution and meaning.

Practice

  1. A column num_children is missing for 4% of rows, MCAR, and has values 0 to 6 with 0 as the most common. Which simple method fits?
Answer

most_frequent (the mode, which is 0 here) or the median. Both give an integer that exists in the data. Here 0 is fine as a learned fill because it is the mode, not because "missing means zero"; with MCAR at 4% the choice hardly matters, and an indicator is cheap insurance.

  1. Why is SimpleImputer(strategy="median") inside cross_val_score safe, while X = X.fillna(X.median()) before it is not?
Answer

Inside the pipeline, each training fold computes its own median and applies it to its validation fold, so the validation rows never influence their own preprocessing. The fillna before CV computes one median from all rows, including every validation fold.

Test yourself

An income column is strongly right-skewed with a few very large values. Which simple fill value is usually more typical?

  1. The mean
  2. The median
  3. Zero
  4. The maximum

Why is fillna(0) dangerous for a column like 'exercise minutes per day'?

  1. Zero is not a number
  2. Zero is a real, meaningful value, so unknowns get merged with people who really did not exercise
  3. It is slow
  4. It changes the dtype

Where must the median used for imputation come from?

  1. All rows, including the test set
  2. The test set
  3. The training data (each training fold inside cross-validation)
  4. A random sample of all rows

For a categorical column region with 15% missing, what does a constant 'Unknown' keep that the mode does not?

  1. Nothing
  2. The information that the value was missing, as its own category
  3. The order of the categories
  4. The original row order