我如何计算以下数组中的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对象没有属性计数
当前回答
Numpy为此提供了一个模块。只是一个小hack。将输入数组作为箱子。
numpy.histogram(y, bins=y)
输出是2个数组。一个是数值本身,另一个是相应的频率。
其他回答
对于您的情况,还可以查看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
你有一个只有1和0的特殊数组。一个技巧就是使用
np.mean(x)
也就是数组中1的百分比。另外,使用
np.sum(x)
np.sum(1-x)
会给出数组中1和0的绝对值。
这里我有一些东西,通过它你可以计算特定数字的出现次数: 根据你的代码
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.
因为ndarray只包含0和1, 您可以使用sum()来获得1的出现次数 和len()-sum()来得到0的出现情况。
num_of_ones = sum(array)
num_of_zeros = len(array)-sum(array)
我会使用np.where:
how_many_0 = len(np.where(a==0.)[0])
how_many_1 = len(np.where(a==1.)[0])