Home > other >  How to use NumPy to sort a multidimensional array from highest to lowest value
How to use NumPy to sort a multidimensional array from highest to lowest value

Time:07-26

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

CodePudding user response:

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()]
  • Related