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

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

y.count(0)为:

numpy。Ndarray对象没有属性计数


当前回答

没有人建议使用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.unique:

import numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
unique, counts = numpy.unique(a, return_counts=True)

>>> dict(zip(unique, counts))
{0: 7, 1: 4, 2: 1, 3: 2, 4: 1}

使用collections.Counter的非numpy方法;

import collections, numpy
a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
counter = collections.Counter(a)

>>> counter
Counter({0: 7, 1: 4, 3: 2, 2: 1, 4: 1})

要计算出现的次数,可以使用np。独特的(数组,return_counts = True):

In [75]: boo = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
 
# use bool value `True` or equivalently `1`
In [77]: uniq, cnts = np.unique(boo, return_counts=1)
In [81]: uniq
Out[81]: array([0, 1])   #unique elements in input array are: 0, 1

In [82]: cnts
Out[82]: array([8, 4])   # 0 occurs 8 times, 1 occurs 4 times
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 (val)伯爵tolist()。

val为0或1

因为python列表有一个原生函数count,所以在使用该函数之前转换为list是一个简单的解决方案。

如果你正在处理非常大的数组,使用生成器可能是一个选择。这里的好处是,这种方法适用于数组和列表,你不需要任何额外的包。此外,您不会使用那么多内存。

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