Getting indices of both null and nonzero elements in an array

I need to find the signs of both null and nonzero array elements.

In other words, I want to find additional indexes from numpy.nonzero() .

The way I know this is as follows:

 indices_zero = numpy.nonzero(array == 0) indices_nonzero = numpy.nonzero(array != 0) 

This, however, means finding the array twice, which is inefficient for large arrays. Is there an efficient way to do this with numpy?

+6
source share
3 answers

Assuming you already have a range to use numpy.arange(len(array)) , just get and save the logical indexes:

 bindices_zero = (array == 0) 

then when you really need integer indices you can do

 indices_zero = numpy.arange(len(array))[bindices_zero] 

or

 indices_nonzero = numpy.arange(len(array))[~bindices_zero] 
+6
source

You can use logical indexing:

 In [82]: a = np.random.randint(-5, 5, 100) In [83]: a Out[83]: array([-2, -1, 4, -3, 1, -2, 2, -1, 2, -1, -3, 3, -3, -4, 1, 2, 1, 3, 3, 0, 1, -3, -4, 3, -5, -1, 3, 2, 3, 0, -5, 4, 3, -5, -3, 1, -1, 0, -4, 0, 1, -5, -5, -1, 3, -2, -5, -5, 1, 0, -1, 1, 1, -1, -2, -2, 1, 1, -4, -4, 1, -3, -3, -5, 3, 0, -5, -2, -2, 4, 1, -4, -5, -1, 3, -3, 2, 4, -4, 4, 2, -2, -4, 3, 4, -2, -4, 2, -4, -1, 0, -3, -1, 2, 3, 1, 1, 2, 1, 4]) In [84]: mask = a != 0 In [85]: a[mask] Out[85]: array([-2, -1, 4, -3, 1, -2, 2, -1, 2, -1, -3, 3, -3, -4, 1, 2, 1, 3, 3, 1, -3, -4, 3, -5, -1, 3, 2, 3, -5, 4, 3, -5, -3, 1, -1, -4, 1, -5, -5, -1, 3, -2, -5, -5, 1, -1, 1, 1, -1, -2, -2, 1, 1, -4, -4, 1, -3, -3, -5, 3, -5, -2, -2, 4, 1, -4, -5, -1, 3, -3, 2, 4, -4, 4, 2, -2, -4, 3, 4, -2, -4, 2, -4, -1, -3, -1, 2, 3, 1, 1, 2, 1, 4]) In [86]: a[-mask] Out[86]: array([0, 0, 0, 0, 0, 0, 0]) 
+3
source

I'm not sure about the numpy built-in method for this, but you can use the old-fashioned for loop, I suppose. Sort of:

 indices_zero = [] indices_nonzero = [] for index in xrange(len(array)): if array[index] == 0: indicies_zero.append(index) else: indicies_nonzero.append(index) 

Something like this should do what you want in just one loop.

+1
source

All Articles