Python 如何让 numpy.argmax 返回所有出现的最大值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17568612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make numpy.argmax return all occurrences of the maximum?
提问by Marieke_W
I'm trying to find a function that returns alloccurrences of the maximum in a given list.
我正在尝试找到一个函数,该函数返回给定列表中所有出现的最大值。
numpy.argmax
however only returns the first occurrence that it finds. For instance:
numpy.argmax
但是只返回它找到的第一次出现。例如:
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
.
只给出索引0
。但我希望它提供所有索引:0, 3, 5
.
回答by jabaldonedo
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.argmax
:“如果多次出现最大值,则返回与第一次出现相对应的索引。” ,因此您将需要另一种策略。
One option you have is using np.argwhere
in combination with np.amax
:
您拥有的一种选择是np.argwhere
结合使用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]
回答by user5838456
Much simpler...
简单多了...
list[list == np.max(list)]
列表[列表== np.max(列表)]
回答by EricRobertBrewer
In case it matters, the following algorithm runs in O(n) instead of O(2n) (i.e., using np.argmax
and then np.argwhere
):
万一重要,以下算法以 O(n) 而不是 O(2n) 运行(即,使用np.argmax
然后np.argwhere
):
def allmax(a):
if len(a) == 0:
return []
all_ = [0]
max_ = a[0]
for i in range(1, len(a)):
if a[i] > max_:
all_ = [i]
max_ = a[i]
elif a[i] == max_:
all_.append(i)
return all_