#encoding:utf-8
import numpy as np
#np.bincount()函数
x=np.array([2,1,3,4,4,3]) #最大的数4,表示有5个bin,索引0-4,
#out[3]=1+1=2,out[4]=1+1=2(统计个数)
print(np.bincount(x))#统计每个元素的个数,并在对应的索引位置显示个数
x2=np.array([2,1,3,4,4,3]) #索引i:0-4 对于每个输出out[i] += weights[输入元素的值所在的位置]
#out[3]=w[2]+w[5]=0.2-0.6=-0.4(统计所占的权重)
w=np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6])
print(np.bincount(x2,weights=w))
x3 = np.array([3, 2, 1, 3, 1])
# 本来bin的数量为4,现在我们指定了参数为7,因此现在bin的数量为7,所以现在它的索引值为0->6
print(np.bincount(x3, minlength=7))
# 我们可以看到x中最大的数为3,因此bin的数量为4,那么它的索引值为0->3
x4 = np.array([3, 2, 1, 3, 1])
# 本来bin的数量为4,现在我们指定了参数为1,那么它指定的数量小于原本的数量,
# 因此这个参数失去了作用,索引值还是0->3
print(np.bincount(x4, minlength=1))
#综合二维数组
x5=np.array([[1,0,1],
[2,1,0],
[0,1,0]])
w5=np.array([[0.1,0.3,1.],
[0.2,0.1,0.],
[0.,1.,0.]])
hist = [np.bincount(b.ravel(), m.ravel(), 4) for b, m in zip(x5, w5)]
print(hist)
print(hist.__len__())
#遍历元组
x61=np.array([[1,0],
[2,1]])
x62=np.array([[1,0],
[0,1]])
w61=np.array([[0.1,0.3],
[0.2,0.1]])
w62=np.array([[0.2,0.1],
[0.2,0.2]])
x6=x61,x62 #两个ndArray类型组成的元组
w6=w61,w62
hist2 = [np.bincount(b.ravel(), m.ravel(), 3) for b, m in zip(x6, w6)]
print(hist2)
print(hist2.__len__())
输出结果:
[0 1 1 2 2]
[ 0. 0.5 0.3 -0.4 1.7]
[0 2 1 2 0 0 0]
[0 2 1 2]
#list对象
[array([0.3, 1.1, 0. , 0. ]), array([0. , 0.1, 0.2, 0. ]), array([0., 1., 0., 0.])]
3
[array([0.3, 0.2, 0.2]), array([0.3, 0.4, 0. ])]
2
参考链接:https://blog.youkuaiyun.com/xlinsist/article/details/51346523