Sort numpy array by sum

I want to sort a numpy array according to the sum. Sort of

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 need an array: result = np.array ([2, 1, 3, 8], [0, 3, 2, 1]]

What is the smartest and fastest way to do this?

+6
source share
1 answer

With the same code from your question, you can simply use the optional axis argument for np.take (the default is a flattened array, for the reason that you only get the first line, see the documentation ):

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

Or you can use fantastic indexing:

 >>> a[:,idx] array([[2, 1, 3, 8], [0, 3, 2, 1]]) 
+5
source

Source: https://habr.com/ru/post/896163/


All Articles