我如何计算以下数组中的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为此提供了一个模块。只是一个小hack。将输入数组作为箱子。
numpy.histogram(y, bins=y)
输出是2个数组。一个是数值本身,另一个是相应的频率。
其他回答
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 == 0).sum() and (y == 1).sum()
E.g.
import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
num_zeros = (y == 0).sum()
num_ones = (y == 1).sum()
利用a系列提供的方法:
>>> import pandas as pd
>>> y = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
>>> pd.Series(y).value_counts()
0 8
1 4
dtype: int64
要计算出现的次数,可以使用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
如果你不想使用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函数做了几乎相同的事情,但这个更透明。