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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.