Impute missing values with train medians and add missing-indicator columns
Why it matters Credit, health and churn datasets are full of gaps, and median plus a missing flag is the strong simple baseline that most tabular pipelines start from.
The fact that a value is missing is often a signal by itself, so imputers can append a 0/1 'was missing' column.
Write impute_median_indicator(X_train, X_test). Inputs are 2D float arrays with np.nan for missing values. Learn each column's median from X_train ignoring NaN. Return a float array that is X_test with NaN replaced by those medians, followed by one indicator column for each column that had at least one NaN in X_train (in column order). The indicator is 1.0 where X_test was NaN, else 0.0. A test column with NaN but no NaN in train is still imputed, just without an indicator.
def impute_median_indicator(X_train, X_test)Example
X_train [[1, nan], [2, 4], [10, 6]], X_test [[nan, nan], [3, 5]] gives [[2.0, 5.0, 1.0], [3.0, 5.0, 0.0]].
Understand the idea
Imputation fills holes in a table. The median is a safe filler because it ignores extreme values: in 1, 2, 10 the median is 2, while the mean is 4.33. We also add a small yes/no column saying 'this was missing', because people who skip a form field often behave differently from those who fill it.
Worked example: train column 2 is [nan, 4, 6], so its median is 5 and, since it had a gap in train, it gets an indicator column. Column 1 is [1, 2, 10] with median 2 and no gaps, so no indicator. Test row [nan, nan] becomes [2, 5] plus indicator 1. Test row [3, 5] stays [3, 5] plus indicator 0.
Rule: x_filled = x if present else median_train; indicator = 1 if x was missing, only for columns missing in train.
Fix the set of indicator columns at fit time so train and test always have the same width. This pattern is standard before linear models and boosted trees.
Shapes and data flow
X_test (m, d) -> filled (m, d) + indicators (m, c) -> (m, d + c)