Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, numpy array code not working for NaN elements

I've created a code that searches the array (3 dimensioanl, (x,y,values)) for the biggest values in the given x and y coordinates, but it doesnt work when values are NaNs.

Here's the code I have so far:

table = np.amax(t, axis = 2)
elements = np.isnan(table)
numbers = table[~elements]
x = np.reshape(numbers, (4, -1))
return np.array(x)

So, for:

t = np.array([[[ np.NaN,  np.NaN,  8.7],
    [ 12.6,  4.9,  8.2]],

   [[ 8.4,   np.NaN,   4.9],
    [  66.8,   np.NaN,   78.6]],

   [[ np.NaN,   81.9,   61.5],
    [ np.NaN,   94.2,  1.3 ]],

   [[ 15.6,  np.NaN,  77.4],
    [ 28.2,  8.3,  8.7]]])

The answer should be:

array([[ 8.7  12.6]
   [ 8.4   78.6]
   [  81.9  94.2 ]
   [ 77.4  28.2]])

It seems to me that np.amax ignores the actual biggest value and just returns a NaN?

like image 298
Jana Avatar asked Jan 01 '26 15:01

Jana


1 Answers

Simply use np.nanmax -

In [140]: t = np.array([[[ np.NaN,  np.NaN,  8.7],
     ...:     [ 12.6,  4.9,  8.2]],
     ...:    [[ 8.4,   np.NaN,   4.9],
     ...:     [  66.8,   np.NaN,   78.6]],
     ...:    [[ np.NaN,   81.9,   61.5],
     ...:     [ np.NaN,   94.2,  1.3 ]],
     ...:    [[ 15.6,  np.NaN,  77.4],
     ...:     [ 28.2,  8.3,  8.7]]])

In [141]: np.nanmax(t,axis=-1)
Out[141]: 
array([[  8.7,  12.6],
       [  8.4,  78.6],
       [ 81.9,  94.2],
       [ 77.4,  28.2]])
like image 57
Divakar Avatar answered Jan 03 '26 15:01

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!