gpt4 book ai didi

numpy - 如何在numpy.ndarray中找到最大值的最后一次出现

转载 作者:行者123 更新时间:2023-12-03 21:17:10 24 4
gpt4 key购买 nike

我有一个 numpy.ndarray,其中最大值通常会出现不止一次。

编辑:这与 numpy.argmax: how to get the index corresponding to the *last* occurrence, in case of multiple occurrences of the maximum values 略有不同因为作者说

Or, even better, is it possible to get a list of indices of all the occurrences of the maximum value in the array?



而在我的情况下,获得这样的 list 可能会非常昂贵

是否可以使用类似 numpy.argmax 的方法找到最大值最后一次出现的索引? ?我只想找到最后一次出现的索引,而不是所有出现的数组(因为可能有数百个)

例如,这将返回第一次出现的索引,即 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数组的反向 View :

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 不会复制数组,而是使用 stride 创建原始 View 。以相反的顺序访问它。
id(a) == id(b.base) # True

关于numpy - 如何在numpy.ndarray中找到最大值的最后一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8768540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com