0

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 and I get that with

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

But now 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?

Unknown Coder
  • 6,625
  • 20
  • 79
  • 129
  • 2
    Possible duplicate of [How do I get indices of N maximum values in a NumPy array?](https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array) – DavidG Oct 30 '18 at 16:04
  • 1
    Have you looked at https://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy? – Omkar Neogi Oct 30 '18 at 16:06

4 Answers4

4

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.

piripiri
  • 1,925
  • 2
  • 18
  • 35
2

just remove the highest value and then use int(np.argmax(values))

Brokkoli 71
  • 141
  • 9
1
np.argsort(values)

Returns

array([0, 4, 3, 5, 2, 1])
John Rouhana
  • 538
  • 3
  • 15
1

Method 1 - using python lists:

values = [0.1, 0.9, 0.8, 0.65, 0.2, 0.7]
#Create a copy of the list
vals = values[:]
print(vals)
for i in range(len(vals)):
    m = max(vals)
    print(i+1,'-',values.index(m),'-',m)
    vals.remove(m)

Method 2 - using numpy as explained by piripiri:

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

for i in range(len(values)):
    print(i+1,'-',indices[i],'-',values[indices[i]])
Nathan
  • 471
  • 2
  • 12