Fill the Holes

Machine Learning in CodeEasy+10 XP+10

Fill the Holes

A sensor logs one reading per hour, but sometimes it drops out. A missing reading is stored as None.

Task: write fill_gaps(values, strategy).

  • values is a list of numbers with some None entries. At least one value is not None.
  • strategy is "mean", "median" or "most_frequent".
  • Fill the gaps with a SimpleImputer(strategy=strategy) fitted on these values.
  • Return the filled list, each value rounded to 2 decimal places.
  • For "most_frequent" with a tie, the imputer picks the smallest of the tied values. You don't need to do anything special.

Tip: pd.DataFrame({"reading": values}, dtype=float) turns each None into np.nan, which is how the imputer spots a gap.

Examples

values = [150.0, None, 170.0, 130.0, None, 160.0]
strategy = "mean"
returns [150.0, 152.5, 170.0, 130.0, 152.5, 160.0]
values = [3, None, 4, 100, None]
strategy = "median"
returns [3.0, 4.0, 4.0, 100.0, 4.0]

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