How to get first 5 maximum values from numpy array in python?

Viewed 620
x = np.array([3, 4, 2, 1, 7, 8, 6, 5, 9])

I want to get an answer as array([9,8,7,6,5]) and their indices array([8,5,4,6,7]).

I've tried np.amax which only provides a single value.

2 Answers

You can do this (each step is commented for clarity):

import numpy as np
x = np.array([3, 4, 2, 1, 7, 8, 6, 5, 9])

y = x.copy() # <----optional, create a copy of the array
y = np.sort(x) # sort array
y = y[::-1] # reverse sort order
y = y[0:5] # take a slice of the first 5
print(y)

The result:

[9 8 7 6 5]

You can use np.argsort to get the sorted indices. Any by doing -x you can get them in descending order:

indices = np.argsort(-x)

You can get the numbers by doing:

sorted_values = x[indices]

You can then get the slice of just the top 5 by doing:

top5 = sorted_values[:5]
Related