0

Not sure I'm finding my exact use case in the NumPy documentation, so hoping for help.

I have this array:

X = np.array([
            [Larry, 90%],
            [Beth, 100%],
            [Arnold, 90%],
])

And I'm trying to sort these horizontal pairs by the second index (i.e., the percentage) from highest to lowest value so that the result is:

            ([
            [Beth, 100%],
            [Arnold, 90%],
            [Larry, 90%],
])

I tried using argsort, but the expression below didn't work:

X = X[-X[:, 0].argsort()]
1
  • First, to refer to the second index/column, 'X[:, 1]' should be used. Second, to sort, you may want to convert a string to a float number. Commented Jul 26, 2022 at 0:49

1 Answer 1

1
import numpy as np
X = np.array([['Larry', '90%'], ['Beth', '100%'], ['Arnold', '90%']])
X[np.array([-float(num.strip('%'))/100 for num in X[:, 1]]).argsort()]
Sign up to request clarification or add additional context in comments.

1 Comment

Please add an explanation to this answer.

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.