choucavalier
choucavalier

Reputation: 2770

numpy: opposite of nonzero (get indices of zero elements)

numpy.nonzero is useful for getting indices of nonzero elements. It returns a tuple of arrays, each of which contains the indices of nonzero elements for a particular axis.

Is there an equivalent but for zero element instead?

Meaning that for the given numpy array

x = [[1, 2, 0],
     [8, 0, 2],
     [0, 0, 1]]

I could get the indices as follows

ax0_zero_idxs, ax1_zero_idxs = numpy.zero(x)

where

ax0_zero_idxs = [0, 1, 2, 2]
ax1_zero_idxs = [2, 1, 0, 1]

Upvotes: 2

Views: 3390

Answers (1)

Valdi_Bo
Valdi_Bo

Reputation: 30971

Note that x == 0 generates a bool array with each element answering the question: Is corresponding element of x equal to 0?

So you can apply np.nonzero to just this array:

result np.nonzero(x == 0)

Try yourself.

The same way you can get indices of elements meeting any other condition.

Upvotes: 6

Related Questions