Skip to content Skip to sidebar Skip to footer

How To Sort A Matrix In The Ascending Order By The Sum Of Its Row In 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 f

Solution 1:

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]]

Solution 2:

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))]

Post a Comment for "How To Sort A Matrix In The Ascending Order By The Sum Of Its Row In Python?"