numpy.bincount#
- numpy.bincount(x, /, weights=None, minlength=0)#
计算非负整数数组中每个值出现的次数。
箱子的数量(大小为 1)比 x 中的最大值多一个。如果指定了 minlength,则输出数组中至少有此数量的箱子(但如果需要,它会更长,具体取决于 x 的内容)。每个箱子表示其索引值在 x 中出现的次数。如果指定了 weights,则输入数组将根据权重进行加权,即如果值
n出现在位置i,则out[n] += weight[i]而不是out[n] += 1。- 参数:
- x类数组对象,1维,非负整数
输入数组。
- weightsarray_like, optional
权重,与 x 形状相同的数组。
- minlength整数,可选
输出数组的最小箱子数。
- 返回:
- out整数 ndarray
对输入数组进行分箱的结果。out 的长度等于
np.amax(x)+1。
- 引发:
- ValueError
如果输入不是一维的,或者包含负值元素,或者 minlength 为负。
- TypeError
如果输入类型为浮点数或复数。
示例
>>> import numpy as np >>> np.bincount(np.arange(5)) array([1, 1, 1, 1, 1]) >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) array([1, 3, 1, 1, 0, 0, 0, 1])
>>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23]) >>> np.bincount(x).size == np.amax(x)+1 True
输入数组需要是整数数据类型,否则会引发 TypeError
>>> np.bincount(np.arange(5, dtype=float)) Traceback (most recent call last): ... TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'
使用
bincount的一个可能用途是使用weights关键字对数组的可变大小的块执行求和。>>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights >>> x = np.array([0, 1, 1, 2, 2, 2]) >>> np.bincount(x, weights=w) array([ 0.3, 0.7, 1.1])