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

Time:03-27

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 there indices array([8,5,4,6,7])

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

CodePudding user response:

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]

CodePudding user response:

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 = 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]
  • Related