HardData Processing

Impute Missing Values (mean/median)

Data Processing

Hard

Problem

Replace missing values in each feature with that feature's observed mean or median. For a two-dimensional input, compute the statistic independently for every column. Treat a one-dimensional input as one feature. Fill a feature containing only missing values with 0.0. Preserve every observed value and return a floating-point NumPy array without modifying the input.

Theory

Missing data imputation is the process of replacing missing or null values in a dataset with substituted values. Real-world datasets almost always contain missing entries due to sensor failures, survey non-responses, data entry errors, or intentional omissions. Imputation allows analysis to proceed on complete datasets while preserving as much information as possible.


Why Missing Data is Problematic

Algorithm requirements: Many machine learning algorithms cannot handle missing values and will fail or produce errors.

Reduced sample size: Deleting rows with missing values (listwise deletion) can dramatically reduce the dataset, losing valuable information.

Biased results: If data is not missing randomly, deletion can introduce systematic bias.

Feature loss: Deleting columns with missing values loses entire features that might be predictive.


Types of Missing Data Mechanisms

Understanding why data is missing determines the appropriate imputation strategy:

Missing Completely at Random (MCAR):

Missing at Random (MAR):

Missing Not at Random (MNAR):


Simple Imputation Methods

Mean Imputation

Replace missing values with the mean of the observed values for that feature.

x_{imputed} = \bar{x} = \frac{1}{n_{observed}} \sum_{i \in observed} x_i

Advantages:

Disadvantages:


Median Imputation

Replace missing values with the median of the observed values.

Advantages:

Disadvantages:


Mode Imputation

Replace missing categorical values with the most frequent category.

Advantages:

Disadvantages:


Constant Imputation

Replace missing values with a fixed constant (e.g., 0, -1, or a special indicator).

Use cases:

Considerations:


Advanced Imputation Methods

K-Nearest Neighbors (KNN) Imputation

Find the k most similar samples (using observed features) and impute using their values.

For numeric features:

x_{imputed} = \frac{1}{k} \sum_{j \in neighbors} x_j

For categorical features, use the mode (most common value) among neighbors.

Advantages:

Disadvantages:


Multiple Imputation

Generate multiple complete datasets, each with different imputed values, analyze each, and pool results.

Process:

  1. Create m imputed datasets (typically 5-20)
  2. Perform analysis on each dataset
  3. Combine results using Rubin's rules to account for imputation uncertainty

Advantages:

Disadvantages:


Regression Imputation

Predict missing values using a regression model trained on complete cases.

\hat{x}_{missing} = \beta_0 + \beta_1 z_1 + \beta_2 z_2 + ... + \beta_p z_p

Where z_1, ..., z_p are other observed features.

Advantages:

Disadvantages:


Worked Example: Mean Imputation

Dataset (feature values with missing entry):

Sample 1: Age=25, Income=50000 Sample 2: Age=30, Income=NaN (missing) Sample 3: Age=35, Income=70000 Sample 4: Age=40, Income=80000

Step 1 - Calculate mean of observed Income values:

\bar{Income} = \frac{50000 + 70000 + 80000}{3} = 66667

Step 2 - Replace missing value: Sample 2 Income becomes 66667

Result: Sample 1: Age=25, Income=50000 Sample 2: Age=30, Income=66667 Sample 3: Age=35, Income=70000 Sample 4: Age=40, Income=80000


Worked Example: KNN Imputation

Same dataset, using k=2 nearest neighbors based on Age:

Step 1 - Find 2 nearest neighbors to Sample 2 (Age=30):

Nearest neighbors: Samples 1 and 3 (both have distance 5)

Step 2 - Impute using neighbors' Income values:

Income_{imputed} = \frac{50000 + 70000}{2} = 60000

Result: Different from mean imputation because it uses local information based on similar samples.


Handling Multiple Missing Features

When a sample has multiple missing values, strategies include:


Creating Missingness Indicators

In addition to imputing, create binary features indicating whether values were originally missing:

\text{Income\_missing} = \begin{cases} 1 & \text{if Income was NaN} \\ 0 & \text{otherwise} \end{cases}

Why useful:


Where Missing Data Imputation Shows Up

Examples

Example 1

Input
X = [[1, nan], [3, 5]], strategy = "mean"
Output
[[1.0, 5.0], [3.0, 5.0]]
Explanation
The second column has one observed value, so its missing entry is filled with 5.

Example 2

Input
X = [[nan, 2], [nan, 4]], strategy = "median"
Output
[[0.0, 2.0], [0.0, 4.0]]

Example 3

Input
X = [1, nan, 3, nan, 5], strategy = "mean"
Output
[1.0, 3.0, 3.0, 3.0, 5.0]

Hints

  1. Use np.isnan to separate missing and observed entries.
  2. Work column by column for a two-dimensional input and assign into a copied float array.

Requirements

Constraints

Starter Code

import numpy as np

def impute_missing(X: list, strategy: str = "mean") -> np.ndarray:
    """
    Returns a NumPy array with the same shape as X.
    """
    # Write code here
    pass

Test Cases

CaseMatches
Basic meanpublic
All-NaN column medianpublic
1D meanpublic