我如何计算以下数组中的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个数组。一个是数值本身,另一个是相应的频率。

其他回答

利用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

这可以用下面的方法轻松完成

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

将数组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.

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

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