xxx222
xxx222

Reputation: 3244

How to get the indices list of all NaN value in numpy array?

Say now I have a numpy array which is defined as,

[[1,2,3,4],
[2,3,NaN,5],
[NaN,5,2,3]]

Now I want to have a list that contains all the indices of the missing values, which is [(1,2),(2,0)] at this case.

Is there any way I can do that?

Upvotes: 136

Views: 265724

Answers (4)

Ahmet Güneş
Ahmet Güneş

Reputation: 7

An alternative is to use np.ma.masked_invalid(x). This is a simpler way if you want numpy to operate only on the valid values. For example

x = np.ones((2,2))
x[(0,0)] = np.nan
x = np.ma.masked_invalid(x)
np.sum(x)

returns 3

Upvotes: -1

johnnyasd12
johnnyasd12

Reputation: 755

Since x!=x returns the same boolean array with np.isnan(x) (because np.nan!=np.nan would return True), you could also write:

np.argwhere(x!=x)

However, I still recommend writing np.argwhere(np.isnan(x)) since it is more readable. I just try to provide another way to write the code in this answer.

Upvotes: 21

Nickil Maveli
Nickil Maveli

Reputation: 29711

You can use np.where to match the boolean conditions corresponding to Nan values of the array and map each outcome to generate a list of tuples.

>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]

Upvotes: 24

michael_j_ward
michael_j_ward

Reputation: 4559

np.isnan combined with np.argwhere

x = np.array([[1,2,3,4],
              [2,3,np.nan,5],
              [np.nan,5,2,3]])
np.argwhere(np.isnan(x))

output:

array([[1, 2],
       [2, 0]])

Upvotes: 228

Related Questions