我如何计算以下数组中的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对象没有属性计数
当前回答
我会使用np.where:
how_many_0 = len(np.where(a==0.)[0])
how_many_1 = len(np.where(a==1.)[0])
其他回答
如果你正在处理非常大的数组,使用生成器可能是一个选择。这里的好处是,这种方法适用于数组和列表,你不需要任何额外的包。此外,您不会使用那么多内存。
my_array = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
sum(1 for val in my_array if val==0)
Out: 8
using numpy.count
$ a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
$ np.count(a, 1)
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
使用numpy怎么样?count_non0,类似的
>>> import numpy as np
>>> y = np.array([1, 2, 2, 2, 2, 0, 2, 3, 3, 3, 0, 0, 2, 2, 0])
>>> np.count_nonzero(y == 1)
1
>>> np.count_nonzero(y == 2)
7
>>> np.count_nonzero(y == 3)
3
另一个简单的解决方案可能是使用numpy.count_nonzero():
import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
y_nonzero_num = np.count_nonzero(y==1)
y_zero_num = np.count_nonzero(y==0)
y_nonzero_num
4
y_zero_num
8
不要让这个名字误导了你,如果你像例子中那样使用布尔值,它会达到目的的。