在Python中,如何计算ndarray中某些项的出现次数?

2024-03-28 16:52:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我有一个ndarrayy 打印为array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

我正在计算这个数组中有多少个0s和多少个1

但是当我输入y.count(0)y.count(1)时,它会说

numpy.ndarray object has no attribute count

我该怎么办?


Tags: nonumpyobjectcountattribute数组arrayhas
3条回答

使用^{}怎么样,比如

>>> import numpy as np
>>> y = np.array([1, 2, 2, 2, 2, 0, 2, 3, 3, 3, 0, 0, 2, 2, 0])

>>> np.count_nonzero(y == 1)
1
>>> np.count_nonzero(y == 2)
7
>>> np.count_nonzero(y == 3)
3
>>> 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方式

使用^{}

>> import collections, numpy

>>> a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
>>> collections.Counter(a)
Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1})

我个人认为: (y == 0).sum()(y == 1).sum()

例如

import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
num_zeros = (y == 0).sum()
num_ones = (y == 1).sum()

相关问题 更多 >