Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
xxx222 Avatar asked Jun 10 '16 18:06

xxx222


People also ask

How do you find the NaN value of a NumPy array?

To check for NaN values in a Numpy array you can use the np. isnan() method. This outputs a boolean mask of the size that of the original array. The output array has true for the indices which are NaNs in the original array and false for the rest.

How do you find the NaN value of a list?

The math. isnan(value) method takes a number value as input and returns True if the value is a NaN value and returns False otherwise. Therefore we can check if there a NaN value in a list or array of numbers using the math. isnan() method.

How do you find the indices of nonzero elements in NumPy?

nonzero() function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] .


2 Answers

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]]) 
like image 106
michael_j_ward Avatar answered Sep 25 '22 12:09

michael_j_ward


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)] 
like image 41
Nickil Maveli Avatar answered Sep 25 '22 12:09

Nickil Maveli