Imputation: A Typical Value for Every Gap

Data ProcessingEasy+10 XP+10

Imputation: A Typical Value for Every Gap

Real datasets have holes. Most models refuse to run with a single gap in them, so before anything else you have to decide what to put in the empty slots. The simplest honest answer: fill every gap with a typical value from the column itself.

Task: write impute(values, strategy) returning a new list with every gap filled, where strategy is either "mean" or "median".

  • A gap is None. Everything else is a number.
  • Compute the filler from the present values only — the gaps must not count toward the mean, and must not take up slots when you sort for the median.
  • Round the filler to 4 decimal places. Leave the values that were already there exactly as they are.
  • For the median, remember the even-count rule: average the two middle values.
  • There is always at least one present value, so there's always something to compute from.

Which strategy to pick is the real lesson. mean is pulled around by extreme values, so a column with a few huge outliers gets filled with a number that's typical of nothing. median ignores them. Run both on the same list and watch the filler move.

weightrows that arrive later

Two rows have no weight. A model cannot take an empty cell, so something has to go there.

Examples

values = [1, None, 2, None, 9]
strategy = 'mean'
returns [1, 4.0, 2, 4.0, 9]
values = [1, None, 2, None, 9]
strategy = 'median'
returns [1, 2.0, 2, 2.0, 9]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run