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.
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.]])
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.]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With