8

I want to sort an numpy array according to the sum. Something like

import numpy as np
a = np.array([1,2,3,8], [3,0,2,1])
b = np.sum(a, axis = 0)
idx = b.argsort()

Now np.take(a, idx) leads to [2, 1, 3, 8].

But I would like an array: result = np.array([2, 1, 3, 8], [0, 3, 2, 1]]

What is the most clever and fastest way to do that?

1 Answer 1

5

With the same code from your question, you can just use the optional axis argument for np.take (default the flattened array is used, that's the reason you got only the first row, see documentation):

>>> np.take(a, idx, axis=1)
array([[2, 1, 3, 8],
       [0, 3, 2, 1]])

Or you can use fancy indexing:

>>> a[:,idx]
array([[2, 1, 3, 8],
       [0, 3, 2, 1]])
Sign up to request clarification or add additional context in comments.

Comments

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.