查找 NumPy 数组中出现频率最高的数字 [英] Find the most frequent number in a NumPy array
问题描述
假设我有以下 NumPy 数组:
Suppose I have the following NumPy array:
a = np.array([1,2,3,1,2,1,1,1,3,2,2,1])
如何找到这个数组中出现频率最高的数字?
How can I find the most frequent number in this array?
推荐答案
如果你的列表包含所有非负整数,你应该看看 numpy.bincounts:
If your list contains all non-negative ints, you should take a look at numpy.bincounts:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html
然后可能使用 np.argmax:
and then probably use 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
是处理此类数据的好方法.
For a more complicated list (that perhaps contains negative numbers or non-integer values), you can use np.histogram
in a similar way. Alternatively, if you just want to work in python without using numpy, collections.Counter
is a good way of handling this sort of data.
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))
这篇关于查找 NumPy 数组中出现频率最高的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!