How do I sort a matrix in ascending order by the sum of its row in Python?

The same question is answered here but in MATLAB.

My question is this: give a matrix, sort it in ascending order according to the sum of its rows. That is, if A

is the following matrix:

A = [[9, 8, 7],
     [2, 5, 7], 
     [1, 3, 4]]

      

so I would get:

B = [[1, 3, 4],
     [2, 5, 7], 
     [9, 8, 7]]

      

because the sum of the 1st row A

is 24

, the sum of the 2nd row A

is 14

, and the sum of the third row A

is 8

. Hence, the first line B

will be the third line A

, the second line B

will be the second line A

, and the third line B

will be the first line A

.

I am looking for a solution that uses a built-in function (if possible). I am not looking for an algorithm for this.

+3


source to share


2 answers


There is a built-in function sorted

available that does the trick. Command

sorted(A, key=sum)

      



gives the desired output:

[[1, 3, 4], [2, 5, 7], [9, 8, 7]]

      

+6


source


If you are working with NumPy this would be

B = A[np.argsort(A.sum(axis=1))]

      

where the call sum

calculates the sum of each row, argsort

calculates the indices of the smallest, second smallest, etc. sums, but A[...]

selects rows at these indices. This assumes A is a NumPy array and not a list of lists.



To do the same with columns it would be

B = A[:, np.argsort(A.sum(axis=0))]

      

+3


source







All Articles