如何使numpy.argmax返回所有出现的最大值? [英] How to make numpy.argmax return all occurrences of the maximum?
问题描述
我正在尝试找到一个函数,该函数返回给定列表中出现的最大值的所有个.
I'm trying to find a function that returns all occurrences of the maximum in a given list.
numpy.argmax
但是仅返回第一个找到的事件.例如:
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
仅提供索引0
.但我希望它给出所有索引:0, 3, 5
.
gives only index 0
. But I want it to give all indices: 0, 3, 5
.
推荐答案
如np.argmax
的文档所述:如果多次出现最大值,则返回对应于第一次出现的索引." ,因此您将需要另一种策略.
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.
您可以使用的一个选项是将np.argwhere
与np.amax
结合使用:
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]
这篇关于如何使numpy.argmax返回所有出现的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!