如何在numpy.ndarray中找到最大值的最后一次出现 [英] How to find last occurrence of maximum value in a numpy.ndarray
问题描述
我有一个numpy.ndarray,其中的最大值通常会出现多次.
I have a numpy.ndarray in which the maximum value will mostly occur more than once.
这与 numpy.argmax有细微的不同:在多次出现的情况下,如何获取对应于* last *出现的索引最大值,因为作者说
或者更好的是,是否可以获得数组中所有出现的最大值的索引的列表?
Or, even better, is it possible to get a list of indices of all the occurrences of the maximum value in the array?
在我看来,获得这样的列表可能证明非常昂贵
whereas in my case getting such a list may prove very expensive
是否可以通过使用类似numpy.argmax
的方法来找到最后一次出现的最大值的索引?我想只查找最后一次出现的索引,而不是所有出现的数组(因为可能有数百个出现)的索引
Is it possible to find the index of the last occurrence of the maximum value by using something like numpy.argmax
? I want to find only the index of the last occurrence, not an array of all occurrences (since several hundreds may be there)
例如,这将返回第一次出现的索引,即2
For example this will return the index of the first occurrence ie 2
import numpy as np
a=np.array([0,0,4,4,4,4,2,2,2,2])
print np.argmax(a)
但是我希望它输出5.
推荐答案
numpy.argmax
仅返回第一次出现的索引.您可以将argmax
应用于数组的反向视图:
numpy.argmax
only returns the index of the first occurrence. You could apply argmax
to a reversed view of the array:
import numpy as np
a = np.array([0,0,4,4,4,4,2,2,2,2])
b = a[::-1]
i = len(b) - np.argmax(b) - 1
i # 5
a[i:] # array([4, 2, 2, 2, 2])
请注意,numpy不会复制数组,而是使用步幅,以相反的顺序对其进行访问.
Note numpy doesn't copy the array but instead creates a view of the original with a stride that accesses it in reverse order.
id(a) == id(b.base) # True
这篇关于如何在numpy.ndarray中找到最大值的最后一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!