首页  >  文章  >  后端开发  >  如何计算 NumPy 数组中元素的出现次数?

如何计算 NumPy 数组中元素的出现次数?

Barbara Streisand
Barbara Streisand原创
2024-10-20 21:47:02529浏览

How to Count Occurrences of Elements in a NumPy Array?

计算 ndarray 中项目的出现次数

要计算 NumPy 数组中特定值的出现次数,可以使用多种方法。

使用 numpy.unique 函数:

<code class="python">import numpy

y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

unique, counts = numpy.unique(y, return_counts=True)

print(dict(zip(unique, counts)))</code>

此方法生成一个字典,其中唯一值作为键,其相应的计数作为值。在上面的示例中,它将返回:

{0: 7, 1: 4}

或者,可以使用集合来采用非 NumPy 方法。计数器:

<code class="python">import collections, numpy

y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

counter = collections.Counter(y)

print(counter)</code>

此方法还会返回一个字典,其中包含与 numpy.unique 方法相同的键值对:

Counter({0: 7, 1: 4})

以上是如何计算 NumPy 数组中元素的出现次数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn