How to make numpy.argmax return all occurrences of

2019-02-07 16:26发布

问题:

I'm trying to find a function that returns all occurrences of the maximum in a given list.

numpy.argmax however only returns the first occurrence that it finds. For instance:

from numpy import argmax

list = [7, 6, 5, 7, 6, 7, 6, 6, 6, 4, 5, 6]
winner = argmax(list)

print winner

gives only index 0. But I want it to give all indices: 0, 3, 5.

回答1:

As documentation of np.argmax says: "In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.", so you will need another strategy.

One option you have is using np.argwhere in combination with np.amax:

>>> import numpy as np
>>> listy = [7, 6, 5, 7, 6, 7, 6, 6, 6, 4, 5, 6]
>>> winner = np.argwhere(listy == np.amax(listy))
>>> print(winner)
 [[0]
  [3]
  [5]]
>>> print(winner.flatten().tolist()) # if you want it as a list
[0, 3, 5]


回答2:

Much simpler...

list[list == np.max(list)]



标签: python numpy max