Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array columns based upon sum

Tags:

python

numpy

Let's suppose I have an array as such:

np.array([1., 1., 0.],
       [0., 4., 0.],
       [8., 0., 8.],
       [0., 0., 0.],
       [5., 0., 0.],
       [2., 2., 2.]])

With column[0] summing to 16, column[1] to 6 and column[2] to 10.

How do I efficiently in Numpy re-arrange the array by column value greatest to least? In the above example, column[0] would remain in place and column[1] and column[2] would switch positions.

like image 306
James Avatar asked Mar 05 '23 11:03

James


2 Answers

You can try sum along axis=0 and use argsort then reverse the array and use:

a[:,np.argsort(a.sum(axis=0))[::-1]]

array([[1., 0., 1.],
       [0., 0., 4.],
       [8., 8., 0.],
       [0., 0., 0.],
       [5., 0., 0.],
       [2., 2., 2.]])
like image 67
Space Impact Avatar answered Mar 27 '23 16:03

Space Impact


Using a combination of np.sum and np.argsort you can achieve this as follows:

x = np.array([[1., 1., 0.],[0., 4., 0.],[8., 0., 8.],[0., 0., 0.],[5., 0., 0.],[2., 2., 2.]])
x[:, np.argsort(-np.sum(x, 0))]
array([[ 1.,  0.,  1.],
       [ 0.,  0.,  4.],
       [ 8.,  8.,  0.],
       [ 0.,  0.,  0.],
       [ 5.,  0.,  0.],
       [ 2.,  2.,  2.]])
like image 37
Silpara Avatar answered Mar 27 '23 15:03

Silpara