Home > Mobile >  Averaging Multiple Arrays in Python
Averaging Multiple Arrays in Python

Time:03-23

I have three 2x2 arrays, with each element filled with floats and NaNs. I want to average each element of the arrays, excluding the NaNs and then input this into a new array.

Is there anyway of doing this without using a for loop and going through each individual element of each array and then using np.Nanmean? I have millions of elements to check so this is exhausting the code.

CodePudding user response:

If you don't mind creating a new array, the following should be quicker than using for loops. Change the list of the 2x2 array in np.stack() with yours.

a1 = np.array([[np.nan, 0], [1, 2]])
a2 = np.array([[3, np.nan], [5, 6]])
a3 = np.array([[7, 8], [np.nan, 10]])
np.nanmean(np.stack([a1, a2, a3]), axis=0)

output:

array([[5., 4.],
       [3., 6.]])
  • Related