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]

1

2 Answers 2

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]]
Sign up to request clarification or add additional context in comments.

Comments

3

If you intend to get numpy operation:

arr = arr[arr[:,0].argsort()]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.