Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

The exact same question is answered here but in MATLAB.

My question is this: Given a matrix, sort it in the 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]]

therefore, I would get:

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

because the sum of the 1st row of A is 24, the sum of the 2nd row of A is 14, and the sum of the 3rd row of A is 8. Hence, the 1st row of B will be the 3rd row of A, the 2nd row of B will be the 2nd row of A, and the 3rd row of B will be the 1st row of A.

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

like image 623
drzbir Avatar asked Dec 03 '25 23:12

drzbir


2 Answers

There is a built-in function, sorted, available that does the trick. The command

sorted(A, key=sum)

gives you the desired output:

[[1, 3, 4], [2, 5, 7], [9, 8, 7]]
like image 70
Cleb Avatar answered Dec 07 '25 05:12

Cleb


If you're working with NumPy, this would be

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

where the sum call computes the sum of each row, argsort computes the indices of the smallest, second-smallest, etc. sums, and A[...] selects the rows at those indices. This is assuming A is a NumPy array, rather than a list of lists.

To do the same with columns, it would be

B = A[:, np.argsort(A.sum(axis=0))]
like image 32
user2357112 supports Monica Avatar answered Dec 07 '25 06:12

user2357112 supports Monica