我如何计算以下数组中的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对象没有属性计数
当前回答
如果你不想使用numpy或collections模块,你可以使用字典:
d = dict()
a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
for item in a:
try:
d[item]+=1
except KeyError:
d[item]=1
结果:
>>>d
{0: 8, 1: 4}
当然,你也可以使用if/else语句。 我认为Counter函数做了几乎相同的事情,但这个更透明。
其他回答
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
老实说,我发现最容易转换为熊猫系列或DataFrame:
import pandas as pd
import numpy as np
df = pd.DataFrame({'data':np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])})
print df['data'].value_counts()
或者是Robert Muil的一句俏皮话:
pd.Series([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]).value_counts()
因为ndarray只包含0和1, 您可以使用sum()来获得1的出现次数 和len()-sum()来得到0的出现情况。
num_of_ones = sum(array)
num_of_zeros = len(array)-sum(array)
筛选并使用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.
没有人建议使用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)) !