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

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

y.count(0)为:

numpy。Ndarray对象没有属性计数


当前回答

你有一个只有1和0的特殊数组。一个技巧就是使用

np.mean(x)

也就是数组中1的百分比。另外,使用

np.sum(x)
np.sum(1-x)

会给出数组中1和0的绝对值。

其他回答

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

如果你知道它们是0和1

np.sum(y)

给出1的个数。Np.sum (1-y)给出0。

一般来说,如果你想计算0而不是0(但可能是2或3):

np.count_nonzero(y)

给出非零的个数。

但是如果您需要更复杂的东西,我不认为numpy将提供一个很好的计数选项。在这种情况下,转到集合:

import collections
collections.Counter(y)
> Counter({0: 8, 1: 4})

这就像字典一样

collections.Counter(y)[0]
> 8

就我个人而言,我认为: (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()

筛选并使用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.

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

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

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

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