I have a 1D boolean array a, for example
a = numpy.array([0, 1, 0, 0, 1, 1, 1, 0, 1], dtype='bool')
I want to use numpy.where to find the indices of the True elements
idx = numpy.where(a)[0]
Can I assume that the output idx is always sorted in an ascending order? Does numpy.where guarantee that? I am asking this question because the document does not say anything about it and the numpy.where is written in C, which is not obvious to tell how it works.
If absolute maximum speed is not of utmost importance you can simply code out your assumption explicitly:
idx = np.arange(len(a))[a]
That said, np.nonzero(a) is guaranteed to give the indices in order as per the documentation. It's just slightly less explicit than the above, but will be faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With