+2 votes
in Programming Languages by (72.7k points)

Let's say the array is b=np.array([1,0,0,0,1,1,1,0,0,1,1,1,0]). How can I find the indices of all 1 in b?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

You can use numpy.where(). It returns a tuple, so you need to take the first element of the tuple for the result.

Check the following example:

>>> b=np.array([1,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1])

>>> np.where(b==1)[0]

array([ 0,  4,  5,  6,  9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 30, 33, 34],

      dtype=int64)


...