在NumPy数组中查找最频繁的数字


问题内容

假设我有以下NumPy数组:

a = np.array([1,2,3,1,2,1,1,1,3,2,2,1])

如何找到此数组中最频繁的号码?


问题答案:

如果您的列表包含所有非负整数,则应查看numpy.bincounts:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html

然后可能使用np.argmax:

a = np.array([1,2,3,1,2,1,1,1,3,2,2,1])
counts = np.bincount(a)
print(np.argmax(counts))

对于更复杂的列表(可能包含负数或非整数值),可以np.histogram类似的方式使用。另外,如果您只想在python中工作而不使用numpy,collections.Counter则是处理此类数据的一种好方法。

from collections import Counter
a = [1,2,3,1,2,1,1,1,3,2,2,1]
b = Counter(a)
print(b.most_common(1))