我如何计算以下数组中的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
其他回答
如果你不想使用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函数做了几乎相同的事情,但这个更透明。
没有人建议使用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)) !
如果你确切地知道你要找的数字,你可以使用下面的方法;
lst = np.array([1,1,2,3,3,6,6,6,3,2,1])
(lst == 2).sum()
返回2在数组中出现的次数。
你有一个只有1和0的特殊数组。一个技巧就是使用
np.mean(x)
也就是数组中1的百分比。另外,使用
np.sum(x)
np.sum(1-x)
会给出数组中1和0的绝对值。
筛选并使用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.