查找 NumPy 数组中出现频率最高的数字

编程入门 行业动态 更新时间:2024-10-12 03:16:31
本文介绍了查找 NumPy 数组中出现频率最高的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有以下 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:

docs.scipy/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 数组中出现频率最高的数字

本文发布于:2023-11-30 22:08:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651617.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   数字   频率最高   NumPy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!