python - 如何计算 ndarray 中某个项目的出现次数?

如何计算下面数组中01的个数?

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

y.count(0) 给出:

numpy.ndarray object has no attribute count

最佳答案

使用 numpy.unique :

import numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
unique, counts = numpy.unique(a, return_counts=True)

>>> dict(zip(unique, counts))
{0: 7, 1: 4, 2: 1, 3: 2, 4: 1}

非numpy方法使用collections.Counter ;

import collections, numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
counter = collections.Counter(a)

>>> counter
Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1})

https://stackoverflow.com/questions/28663856/

相关文章:

python - 如何在 Python 中获取当前模块中所有类的列表?

python - 默认字典的默认字典?

python - 如何从 Python 中的线程获取返回值?

python - 测试 Python 中是否存在可执行文件?

python - 如何将 time.struct_time 对象转换为 datetime 对象?

python - 从 Django QuerySet 获取 SQL

python - PEP8 的 E128 : continuation line under-ind

javascript - 当您将 Selenium 与 chromedriver 一起使用时,网站可

python - 在 Python 3 中从 Web 下载文件

python - 将标准输出重定向到 Python 中的文件?