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 !

Was it helpful?

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top