In this python numpy program, we will calculate averages without NaNs along a row of an array.
Steps to solve the program
- Import the numpy library as np.
- Create an array using np.array().
- First, remove the NaN values using np.ma.masked_array()
- Calculate averages without NaN values along the rows using np.average() and set the axis equal to 1.
- Print the output.
import numpy as np
x = np.array([[6, 5, np.nan],[np.nan, 9, 1],[7, 8, 2]])
temp = np.ma.masked_array(x,np.isnan(x))
print("Array after removing nan values: \n",temp)
print("\nAverages without NaNs along the said array:")
print(np.average(temp,axis=1))
Output :
Array after removing nan values:
[[6.0 5.0 --]
[-- 9.0 1.0]
[7.0 8.0 2.0]]
Averages without NaNs along the said array:
[5.5 5.0 5.666666666666667]