2

I would like to rearrange the rows in a python numpy array according to descending order of the first column. For Example,

([[2,3,1,8],
  [4,7,5,20],
  [0,-2,2,0]])

to be converted to

([[0,-2,2,0],
  [2,3,1,8],
  [4,7,5,20]])

such that first column converts to [0,2,4] from [2,4,0]

Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
  • Does this answer your question? [Sorting arrays in NumPy by column](https://stackoverflow.com/questions/2828059/sorting-arrays-in-numpy-by-column) – adir abargil Dec 20 '20 at 06:33

2 Answers2

3

Regular sorted does it:

print(sorted([[2,3,1,8], [4,7,5,20], [0,-2,2,0]]))

But if you only want to sort by the first columns, use:

print(sorted([[2,3,1,8], [4,7,5,20], [0,-2,2,0]], key=lambda x: x[0]))

They both output:

[[0, -2, 2, 0], [2, 3, 1, 8], [4, 7, 5, 20]]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
3

If you intend to get numpy operation:

arr = arr[arr[:,0].argsort()]
adir abargil
  • 5,495
  • 3
  • 19
  • 29