在Python中,我有一个打印为array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])的ndarray y
我正在尝试计算这个数组中有多少个0和多少个1。
但当我键入y.count(0)或y.count(1)时,它会显示
numpy.ndarray对象没有count属性
我该怎么办?
发布于 2015-02-23 06:10:26
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})发布于 2016-02-22 17:14:19
那么使用numpy.count_nonzero怎么样呢?
>>> 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发布于 2016-05-06 04:51:54
就我个人而言,我倾向于:(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()https://stackoverflow.com/questions/28663856
复制相似问题