numpy.bincount(x, weights=None, minlength=None)
这个函数功能统计出序列 x 中 0,1,2,3........max(x)每个值出现的次数
import numpy as np x = np.array([0, 1, 1, 3, 2, 1, 9]) #len(x)=7 np.bincount(x)# max(x)=9 0到9共有10个数
import numpy as np
x = np.array([0, 1, 1, 3, 2, 1, 9]) #len(x)=7
np.bincount(x)# max(x)=9 0到9共有10个数
Out[2]:
array([1, 3, 1, 1, 0, 0, 0, 0, 0, 1], dtype=int64)
分析 在x中 0 出现1次 ,1出现3次,2出现1次,3出现1次,4—8出现0次,9出现一次
对于weights 权重则是在对每个元素计数时乘以这个权重默认是权重为1计数时输出1*1 给了权重则是1*weight,x和weights 要一一对应
w1 = np.array([1,1, 1, 1,1,1])
w2 = np.array([0.3, 0.5, 0.2, 0.7,1,2])
# 我们可以看到x中最大的数为4,因此bin的数量为5,那么它的索引值为0->4
x = np.array([2, 1, 3, 4, 4, 3])
np.bincount(x, weights=w1)
# 因此,输出结果为:array([ 0. , 0.5, 0.3, -0.4, 1.7])
Out[10]:
array([0., 1., 1., 2., 2.])
In [11]:
np.bincount(x, weights=w2)
Out[11]:
array([0. , 0.5, 0.3, 2.2, 1.7])
对于minlength则是如果x中的最大值小于minlength则按0到minlength-1中的每个元素计数
x = np.array([2, 1])
np.bincount(x,minlength=9)
array([0, 1, 1, 0, 0, 0, 0, 0, 0], dtype=int64)