我如何计算以下数组中的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对象没有属性计数
当前回答
筛选并使用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.
其他回答
using numpy.count
$ a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
$ np.count(a, 1)
这里我有一些东西,通过它你可以计算特定数字的出现次数: 根据你的代码
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.
您可以使用字典理解来创建简洁的一行代码。更多关于字典理解的内容可以在这里找到
>>> counts = {int(value): list(y).count(value) for value in set(y)}
>>> print(counts)
{0: 8, 1: 4}
这将创建一个字典,将ndarray中的值作为键,并将值的计数分别作为键的值。
当您想要计算该格式数组中某个值的出现次数时,这种方法就可以工作。
对于您的情况,还可以查看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
它还涉及一个步骤,但更灵活的解决方案也适用于2d数组和更复杂的过滤器,即创建一个布尔掩码,然后在掩码上使用.sum()。
>>>>y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
>>>>mask = y == 0
>>>>mask.sum()
8