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

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.



Solution 1:[1]

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]


Solution 2:[2]

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]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ani