Calculate averages without NaNs along a row of an array

In this python numpy program, we will calculate averages without NaNs along a row of an array.

Steps to solve the program
  1. Import the numpy library as np.
  2. Create an array using np.array().
  3. First, remove the NaN values using np.ma.masked_array()
  4. Calculate averages without NaN values along the rows using np.average() and set the axis equal to 1.
  5. 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]
				
			

calculate the sum of all columns of an array

merge two given arrays of identical shape.

Leave a Comment