Back to Practice
#0134

Replace NaN With Column Mean

MediumNumPy25 min20 XP

Problem

Given a 2D NumPy array, return a copy where NaN values are replaced by their column mean ignoring NaNs.

Why This Matters

Mean imputation is not always best, but implementing it teaches masks, indexes, and column-wise statistics.

Function Signature

def fill_nan_column_mean(matrix):

Examples

Example 1
Input[[1, nan], [3, 5]]
Output[[1, 5], [3, 5]]

The second column mean ignoring NaN is 5.

Constraints

  • Return the exact requested structure.
  • Handle normal edge cases cleanly.
  • Prefer readable code over clever shortcuts.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Input[[1, nan], [3, 5]]
Expected[[1, 5], [3, 5]]

The second column mean ignoring NaN is 5.

Hidden Test Categories
multiple NaNsno NaNsdifferent columns