我如何计算以下数组中的0和1的数量?

y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])

y.count(0)为:

numpy。Ndarray对象没有属性计数


当前回答

最简单的方法是,如果没有必要的话做评论

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

其他回答

我会使用np.where:

how_many_0 = len(np.where(a==0.)[0])
how_many_1 = len(np.where(a==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.

如果你确切地知道你要找的数字,你可以使用下面的方法;

lst = np.array([1,1,2,3,3,6,6,6,3,2,1])
(lst == 2).sum()

返回2在数组中出现的次数。

这个函数返回变量在数组中出现的次数:

def count(array,variable):
    number = 0
    for i in range(array.shape[0]):
        for j in range(array.shape[1]):
            if array[i,j] == variable:
                number += 1
    return number
using numpy.count

$ a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]

$ np.count(a, 1)