Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort numpy.array rows by indices

I have 2D numpy.array and a tuple of indices:

a = array([[0, 0], [0, 1], [1, 0], [1, 1]])
ix = (2, 0, 3, 1)

How can I sort array's rows by the indices? Expected result:

array([[1, 0], [0, 0], [1, 1], [0, 1]])

I tried using numpy.take, but it works as I expect only with 1D arrays.

like image 445
niekas Avatar asked Jul 03 '26 20:07

niekas


1 Answers

You can in fact use ndarray.take() for this. The trick is to supply the second argument (axis):

>>> a.take(ix, 0)
array([[1, 0],
       [0, 0],
       [1, 1],
       [0, 1]])

(Without axis, the array is flattened before elements are taken.)

Alternatively:

>>> a[ix, ...]
array([[1, 0],
       [0, 0],
       [1, 1],
       [0, 1]])
like image 92
NPE Avatar answered Jul 05 '26 10:07

NPE



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!