3

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.

1 Answer 1

6

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I didn't know about the second argument of numpy.take.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.