我如何计算以下数组中的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对象没有属性计数
当前回答
最简单的方法是,如果没有必要的话做评论
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
其他回答
利用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转换为列表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
没有人建议使用numpy。Bincount (input, minlength)与minlength = np.size(input),但这似乎是一个很好的解决方案,而且绝对是最快的:
In [1]: choices = np.random.randint(0, 100, 10000)
In [2]: %timeit [ np.sum(choices == k) for k in range(min(choices), max(choices)+1) ]
100 loops, best of 3: 2.67 ms per loop
In [3]: %timeit np.unique(choices, return_counts=True)
1000 loops, best of 3: 388 µs per loop
In [4]: %timeit np.bincount(choices, minlength=np.size(choices))
100000 loops, best of 3: 16.3 µs per loop
numpy之间的加速太疯狂了。unique(x, return_counts=True)和numpy。Bincount (x, minlength=np.max(x)) !
一个普遍而简单的答案是:
numpy.sum(MyArray==x) # sum of a binary list of the occurence of x (=0 or 1) in MyArray
这将导致这完整的代码作为例子
import numpy
MyArray=numpy.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]) # array we want to search in
x=0 # the value I want to count (can be iterator, in a list, etc.)
numpy.sum(MyArray==0) # sum of a binary list of the occurence of x in MyArray
现在,如果MyArray是多维的,你想要计算值在直线(= pattern以后)上分布的次数。
MyArray=numpy.array([[6, 1],[4, 5],[0, 7],[5, 1],[2, 5],[1, 2],[3, 2],[0, 2],[2, 5],[5, 1],[3, 0]])
x=numpy.array([5,1]) # the value I want to count (can be iterator, in a list, etc.)
temp = numpy.ascontiguousarray(MyArray).view(numpy.dtype((numpy.void, MyArray.dtype.itemsize * MyArray.shape[1]))) # convert the 2d-array into an array of analyzable patterns
xt=numpy.ascontiguousarray(x).view(numpy.dtype((numpy.void, x.dtype.itemsize * x.shape[0]))) # convert what you search into one analyzable pattern
numpy.sum(temp==xt) # count of the searched pattern in the list of patterns
因为ndarray只包含0和1, 您可以使用sum()来获得1的出现次数 和len()-sum()来得到0的出现情况。
num_of_ones = sum(array)
num_of_zeros = len(array)-sum(array)