3

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.

Community
  • 1
  • 1
drzbir
  • 419
  • 1
  • 6
  • 15
  • use the `sort` method of the list object (or the `sorted` free function) and pass `sum` as the `key`. So `sorted(A, key=sum)` should work (or something like it, I haven't tested). – scott_fakename May 30 '15 at 02:02

2 Answers2

7

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]]
Cleb
  • 25,102
  • 20
  • 116
  • 151
  • 1
    Thanks. And if I want to use the sum of the columns? – drzbir May 30 '15 at 02:10
  • Then you could transpose your matrix first and then apply the same function. – Cleb May 30 '15 at 02:13
  • Thanks. I missed that, my bad. – drzbir May 30 '15 at 02:14
  • I am recieving this error, can someone add in answer how to resolve this? ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() – mattsmith5 Apr 01 '21 at 07:39
  • @mattsmith5: probably best to open a new question and link to this one as reference. Right now it is difficult to help as we don't know your input. – Cleb Apr 01 '21 at 07:54
  • hi @Cleb coworker just posted question here https://stackoverflow.com/questions/66900594/python-sort-numpy-valueerror-the-truth-value-of-an-array-with-more-than-one-ele – mattsmith5 Apr 01 '21 at 08:03
3

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))]
user2357112
  • 260,549
  • 28
  • 431
  • 505