我如何计算以下数组中的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对象没有属性计数
当前回答
如果你确切地知道你要找的数字,你可以使用下面的方法;
lst = np.array([1,1,2,3,3,6,6,6,3,2,1])
(lst == 2).sum()
返回2在数组中出现的次数。
其他回答
就我个人而言,我认为: (y == 0).sum() and (y == 1).sum()
E.g.
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()
将数组y转换为列表l,然后执行l.count(1)和l.count(0)
>>> y = numpy.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
>>> l = list(y)
>>> l.count(1)
4
>>> l.count(0)
8
筛选并使用len
使用len是另一种选择。
A = np.array([1,0,1,0,1,0,1])
假设我们想要0的出现次数。
A[A==0] # Return the array where item is 0, array([0, 0, 0])
现在,用len把它包起来。
len(A[A==0]) # 3
len(A[A==1]) # 4
len(A[A==7]) # 0, because there isn't such item.
利用a系列提供的方法:
>>> import pandas as pd
>>> y = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
>>> pd.Series(y).value_counts()
0 8
1 4
dtype: int64
最简单的方法是,如果没有必要的话做评论
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