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

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

Barbara Streisand
Barbara Streisand原创
2024-10-20 21:50:30831浏览

How to Count Occurrences of Elements in NumPy Arrays?

统计 NumPy 数组中的出现次数

NumPy 数组广泛用于数值计算,常见的任务是统计特定元素的出现次数在他们之内。然而,与列表和其他 Python 数据结构不同,NumPy 数组没有内置的 count 方法。

使用 NumPy 的 unique

numpy.unique 函数可以是用于确定数组中的唯一值及其各自的计数。它采用可选参数 return_counts,当设置为 True 时,将返回唯一值及其相应的计数。例如:

<code class="python">import numpy

# Create a NumPy array
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

# Obtain unique values and their counts
unique, counts = numpy.unique(y, return_counts=True)

# Convert the results to a dictionary for ease of access
results = dict(zip(unique, counts))

print(results)  # Output: {0: 7, 1: 4}</code>

非 NumPy 方法:使用 collections.Counter

或者,您可以使用 NumPy 外部的 collections.Counter 类。此类专门设计用于计算任何可迭代对象中的出现次数,包括 NumPy 数组:

<code class="python">import collections

# Use the Counter class to tally the occurrences of each element
counter = collections.Counter(y)

# Print the Counter object to view the occurrences
print(counter)  # Output: Counter({0: 7, 1: 4})</code>

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

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