我如何计算以下数组中的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对象没有属性计数
当前回答
筛选并使用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.
其他回答
如果你正在处理非常大的数组,使用生成器可能是一个选择。这里的好处是,这种方法适用于数组和列表,你不需要任何额外的包。此外,您不会使用那么多内存。
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
老实说,我发现最容易转换为熊猫系列或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()
Numpy为此提供了一个模块。只是一个小hack。将输入数组作为箱子。
numpy.histogram(y, bins=y)
输出是2个数组。一个是数值本身,另一个是相应的频率。
using numpy.count
$ a = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
$ np.count(a, 1)
使用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})