我如何计算以下数组中的0和1的数量?
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
y.count(0)为:
numpy。Ndarray对象没有属性计数
我如何计算以下数组中的0和1的数量?
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
y.count(0)为:
numpy。Ndarray对象没有属性计数
当前回答
dict(zip(*numpy.unique(y, return_counts=True)))
只是复制了Seppo Enarvi的评论,这应该是一个正确的答案
其他回答
使用numpy怎么样?count_non0,类似的
>>> 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
因为ndarray只包含0和1, 您可以使用sum()来获得1的出现次数 和len()-sum()来得到0的出现情况。
num_of_ones = sum(array)
num_of_zeros = len(array)-sum(array)
对于您的情况,还可以查看numpy.bincount
In [56]: a = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
In [57]: np.bincount(a)
Out[57]: array([8, 4]) #count of zeros is at index 0, i.e. 8
#count of ones is at index 1, i.e. 4
这里我有一些东西,通过它你可以计算特定数字的出现次数: 根据你的代码
count_of_zero=list(y[y==0]).count(0)
print(count_of_zero)
// according to the match there will be boolean values and according
// to True value the number 0 will be return.
最简单的方法是,如果没有必要的话做评论
import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
count_0, count_1 = 0, 0
for i in y_train:
if i == 0:
count_0 += 1
if i == 1:
count_1 += 1
count_0, count_1