Fill Missing Values (NaN) With Median

Basics
BasicsData CleaningImputationGoogleMetaAmazon

Problem

Implement fill_missing_median(x) that replaces all NaN values in a 1D numeric array with the median of the non-missing values.

Why It Matters: Median imputation handles skewed real-world features (income, housing prices) far more robustly than mean imputation without dropping training rows.

Sample Inputs & Expected Outputs

Example 1 — Single NaN

>>> fill_missing_median([10.0, np.nan, 20.0, 30.0])
array([10., 20., 20., 30.])

Non-missing values [10, 20, 30] have median 20.0.

Example 2 — Outlier-heavy array

>>> fill_missing_median([1.0, 2.0, 3.0, 1000.0, np.nan])
array([1., 2., 3., 1000., 2.5])

Median of [1, 2, 3, 1000] is 2.5 (unaffected by the 1000 outlier).

Example 3 — Multiple NaNs

>>> fill_missing_median([np.nan, 5.0, np.nan, 15.0])
array([10., 5., 10., 15.])

Both NaNs are replaced by median(5, 15) = 10.0.

Constraints & Edge Cases

  • Do not mutate the input array in-place.
  • Return a 1D float NumPy array.

Constraints & Evaluation Criteria

  • Do not mutate the input array in-place.
  • Return a 1D float NumPy array.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[10, nan, 20, 30]
Expected Output / Criteria
[10, 20, 20, 30]