Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does numpy.where always output the indices in an ascending order?

Tags:

python

numpy

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.

like image 860
f. c. Avatar asked Nov 22 '25 22:11

f. c.


1 Answers

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.

like image 174
orlp Avatar answered Nov 25 '25 13:11

orlp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!