![](/img/trans.png)
[英]numpy.argmax: how to get the index corresponding to the *last* occurrence, in case of multiple occurrences of the maximum values
[英]How to make numpy.argmax return all occurrences of the maximum?
我正在嘗試找到一個函數,該函數返回給定列表中所有出現的最大值。
然而numpy.argmax
只返回它找到的第一次出現。 例如:
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
。
正如np.argmax
文檔所說: “如果多次出現最大值,則返回與第一次出現相對應的索引。” ,因此您將需要另一種策略。
您擁有的一種選擇是將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]
萬一重要,以下算法以 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_
與其他答案相比,如果您使用np.flatnonzero
:
>>> import numpy as np
>>> your_list = np.asarray([7, 6, 5, 7, 6, 7, 6, 6, 6, 4, 5, 6])
>>> winners = np.flatnonzero(your_list == np.max(your_list))
>>> winners
array([0, 3, 5])
如果你想要一個列表:
>>> winners.tolist()
[0, 3, 5]
簡單多了...
列表[列表== np.max(列表)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.