获取 numpy 数组中具有最大计数的每个值

get every value with maximum count in a numpy array

例如,我有以下数组:

x = [1,2,3,3,4,5,6,6,7,8]

我需要以下输出:

y = [3,6]

因此,它类似于模式,但如果多个值具有相同的最大计数,则可以 return 多个值。什么是有效的方法?谢谢

只需使用 np.uniquereturn_counts = True

u, c = np.unique(x, return_counts = True)
y = u[c == c.max()]

如果x只包含非负整数,并且max(x)不是太大,可以使用numpy.bincount:

In [230]: x = [1,2,3,3,4,5,6,6,7,8]

In [231]: counts = np.bincount(x)

In [232]: np.where(counts == counts.max())[0]
Out[232]: array([3, 6])

数组 counts 的长度为 max(x)+1,因此如果 max(x) 很大,您可能不想使用它。

此方法比使用 numpy.unique 快得多。