np.bincount() 解释

np.bincount() 解释

主要作用

统计输入的数组中的每个值在非负整数数组中出现的次数

输入输出参数

输入参数 x, weights=None, minlength=None,注意,x为非负整数数组。

import numpy as np
x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
y = np.bincount(x)
# y: [1 3 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]

y的长度为x中最大的数再加上1,也就是23+1,y的长度为24。

x的每一个值相当于y的索引信息,需要统计重复的数字。比如x中的0出现1次,那么y[0]=1, 1出现3次,y[1]=3,同理,y[23]=1。其余位置索引均为0,因为x中没有出现该数字。

minlength大于x的最大值时,才算是发挥作用,举例说明:

x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
y = np.bincount(x,minlength=3)
# y : [1 3 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]

x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
y = np.bincount(x,minlength=30)
# y : [1 3 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0] 多出6个0

weights需要和x的形状一致,默认为None时,其实就是每次加1,有了weight,对应相加即可。

w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6])  # weights
x = np.array([0, 1, 1, 2, 2, 2])
y = np.bincount(x,  weights=w)
print(y) # [0.3 0.7 1.1]
# y[0]=0.3 y[1]=0.5+0.2 y[2]=0.7+1-0.6

y = np.bincount(x)
print(y) # [1,2,3]

猜你喜欢

转载自blog.csdn.net/qq_44897728/article/details/112261517