Python Practice › NumPy Programs › Program 86
Row averages ignoring NaN
Write a NumPy program to calculate the average of each row, ignoring NaNs.
Input
[[6, 5, nan], [nan, 9, 1], [7, 8, 2]]
Output
[5.5 5. 5.67]
Approach
np.nanmean(axis=1).
Solution
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.