如何在 numpy.ndarray 中找到最大值的最后一次出现 [英] How to find last occurrence of maximum value in a numpy.ndarray

查看:27
本文介绍了如何在 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.

However I want it to output 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 不会复制数组,而是使用 stride 以相反的顺序访问它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆