Neural Mastery
← Practice
Pandas Missing Value Imputation Pipelineeasy

Pandas Missing Value Imputation Pipeline

easy NumPy & Data Wrangling 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Impute missing values across numerical and categorical features in tabular records using Pandas.

Related Skills

Task

Implement impute_missing_values(records, num_strategy, cat_strategy). For numeric columns with missing values, fill with the column mean or median (rounded to 2 decimal places). For non-numeric columns, fill with the mode or string fallback.

Function Signature

impute_missing_values(records: list[dict], num_strategy: str = 'mean', cat_strategy: str = 'mode') -> list[dict]

Examples

Example 1: Numeric Mean and Categorical Mode
Input: records = [{'age': 20, 'city': 'NY'}, {'age': 40, 'city': 'SF'}, {'age': None, 'city': 'NY'}, {'age': 30, 'city': None}] num_strategy = 'mean' cat_strategy = 'mode'
Output: [{'age': 20, 'city': 'NY'}, {'age': 40, 'city': 'SF'}, {'age': 30, 'city': 'NY'}, {'age': 30, 'city': 'NY'}]
Example 2: Numeric Median and Categorical Constant
Input: records = [{'score': 10, 'grade': 'A'}, {'score': 20, 'grade': None}, {'score': 90, 'grade': 'B'}] num_strategy = 'median' cat_strategy = 'missing'
Output: [{'score': 10, 'grade': 'A'}, {'score': 20, 'grade': 'missing'}, {'score': 90, 'grade': 'B'}]

Constraints

  • records is a list of dictionary rows.
  • num_strategy is either 'mean' or 'median'.
  • cat_strategy is 'mode' or a string replacement.
  • Returns a list of dicts in identical row order with all missing values imputed.
Python3Saved ✓
import pandas as pd
import numpy as np

def impute_missing_values(records: list[dict], num_strategy: str = 'mean', cat_strategy: str = 'mode') -> list[dict]:
"""Impute missing (None/NaN) values in records using pandas.
For numeric columns: fill with mean or median (rounded to 2 decimal places).
For categorical columns: fill with mode or literal placeholder.
Return the cleaned records as list of dicts."""
# Your implementation here
pass

Case 1: Numeric Mean and Categorical Mode
Input: records = [{'age': 20, 'city': 'NY'}, {'age': 40, 'city': 'SF'}, {'age': None, 'city': 'NY'}, {'age': 30, 'city': None}] num_strategy = 'mean' cat_strategy = 'mode'
Expected: [{'age': 20, 'city': 'NY'}, {'age': 40, 'city': 'SF'}, {'age': 30, 'city': 'NY'}, {'age': 30, 'city': 'NY'}]
Case 2: Numeric Median and Categorical Constant
Input: records = [{'score': 10, 'grade': 'A'}, {'score': 20, 'grade': None}, {'score': 90, 'grade': 'B'}] num_strategy = 'median' cat_strategy = 'missing'
Expected: [{'score': 10, 'grade': 'A'}, {'score': 20, 'grade': 'missing'}, {'score': 90, 'grade': 'B'}]