Numpy - difference when using np.isnan directly and saving booleans in a temp. variable

StackOverflow https://stackoverflow.com/questions/22965470

  •  30-06-2023
  •  | 
  •  

Question

I want to remove NaN from a numpy array along the lines, exemple :

A = np.array([[1,2,3,4,5,6],
       [1,2,3,4,5,6],
       [1,2,3,4,nan,6],
       [1,2,3,4,5,6],
       [1,2,3,4,5,6],
       [1,2,3,4,5,6],
       [1,2,nan,4,5,6],
       [1,2,3,4,5,6],
       [nan,2,3,4,5,6]])

I remove them using a direct command, and it works fine :

A1 = A[~np.isnan(A).any(1)]

But if I save the booleans values in a temporary array :

boolAnonan = ~np.isnan(A)  
A2 = A[boolAnonan.any(1)]

It change nothing !

In fact, why get I this ? :

>>> boolAnonan == ~np.isnan(A)
array([[ True,  True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True,  True]], dtype=bool)

>>> ~np.isnan(A).any(1)
array([ True,  True, False,  True,  True,  True, False,  True, False], dtype=bool)

>>> boolAnonan.any(1)
array([ True,  True,  True,  True,  True,  True,  True,  True,  True], dtype=bool)

Any logical explanation ? Thanks !

Était-ce utile?

La solution

You have a precedence problem

~x.y.z

is

~(x.y.z)

not

(~z).y.z

Thus

~np.isnan(A).any(1)

is not the same as

(~np.isnan(A)).any(1)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top