I have a numpy array
with size (1000,6)
and I fill part of it each time during my program. I need to find the first location of zero in this array. for this, I used np.where( array==0)
. but the output is a tuple
of size 2 and each item of it is a numpy array and I do not how can I find the first index of occurring zero in this array. what should I do about this?
CodePudding user response:
The first element of the tuple that you got should be the index you are looking.
CodePudding user response:
The best way would be to use np.argwhere
:
tuple(np.argwhere(a == 0)[0])
If you want to use np.where
, then you can do:
next(zip(*np.where(array == 0)))
That tuple of arrays you got were the indices for each axis. We can zip them together to get coordinate pairs. Then we call next
on the zip iterator to get the first element from it, i.e. the coordinates of the first 0
found by np.where
. You can test that these are the coordinates for the zeros by verifying that the when we use them as indexes for array
it always outputs zero:
[array[x] for x in zip(*np.where(array == 0))]
Both of these approaches have the disadvantage of operating on the entire array, when they ought to stop after the first match. Stopping after the first match is a feature request that can be tracked here: https://github.com/numpy/numpy/issues/2269