NumPy - 查找数组中最常见的值,在平局的情况下使用最大值

NumPy - Find most common value in array, use largest value in case of a tie

关于查找数组中最常见值的问题有很多,但所有这些问题都是 return 平局时的“第一个”元素。我需要绑定元素列表中的最高值,想象一下这样的事情:

import numpy as np

my_array = [1, 1, 3, 3]
most_common = np.bincount(my_array).argmax()

这给了我 1,这显然没有错,但我这里有一个平局结果,我想自己决定在这种情况下我想做什么。对于我的应用程序,如果出现这种平局,我想要 my_array 中的最高值,即 3。我该怎么做?

PS:需要一个 Python 2.7 的答案...抱歉,目前无法更改

不确定如何使用 Numpy 解决此问题,因为无法更改 argmax 的打破平局逻辑,但您可以使用 collections.Counter 轻松实现:

from collections import Counter

my_array = [1, 1, 3, 3]
counter = Counter(my_array)
most_common, num_occurances = max(counter.most_common(), key=lambda x: (x[1], x[0]))

您可以将 argmax 应用于 bincount 的反转输出,然后调整以考虑反转:

In [73]: x
Out[73]: array([3, 0, 2, 3, 1, 0, 1, 3, 2, 1, 1, 2, 1, 3, 3, 4])

In [74]: b = np.bincount(x)

In [75]: b
Out[75]: array([2, 5, 3, 5, 1])

In [76]: most_common = len(b) - 1 - b[::-1].argmax()

In [77]: most_common
Out[77]: 3