Python Practice › NumPy Programs › Program 86

Row averages ignoring NaN

EasyNumPy Programs · 86 of 100

Write a NumPy program to calculate the average of each row, ignoring NaNs.

Advertisement
Input
[[6, 5, nan], [nan, 9, 1], [7, 8, 2]]
Output
[5.5  5.   5.67]

Approach

  1. np.nanmean(axis=1).

Solution

Python
import numpy as npa = np.array([[6, 5, np.nan], [np.nan, 9, 1], [7, 8, 2]])print(np.nanmean(a, axis=1).round(2))
Output
[5.5  5.   5.67]
Note

The third row’s average is 17 / 3 = 5.67; the original sample answer (8.5) was not correct.

Learn the concept

New to this topic? Read the lesson, then come back.

More numpy programs

← All 100 NumPy Programs

Leave a Comment