pythonnumpyranking

Get top-N ranking indices and values, from numpy array


I have a numpy array like the following

values = [0.1, 0.9, 0.8, 0.65, 0.2, 0.7]

I need to know both the value and the index of the top value, which I can get with...

int(np.argmax(values))
max(values)

...but then I also need to know the second-highest and third-highest values from the array and preserve the index accordingly. How can I modify my code to get those values?


Solution

  • You can use np.argsort, it gives you the indices of the largest numbers.

    indices = np.argsort(values)[::-1]
    print(indices)
    

    The [::-1] reverses the list, which is necessary because argsort returns the indices in increasing order. This gives:

    [1, 2, 5, 3, 4, 0]
    

    Then you can use

    values[indices[n]]
    

    to retrieve the n-th largest value.