numpy.bincount#
- numpy.bincount(x, /, weights=None, minlength=0)#
计算非负整数数组中每个值的出现次数。
分箱(大小为 1)的数量比 x 中的最大值大一。如果指定了 minlength,则输出数组中将至少有此数量的分箱(但如有必要,它会更长,具体取决于 x 的内容)。每个分箱给出其索引值在 x 中出现的次数。如果指定了 weights,则输入数组将按其加权,即如果在位置
i
找到值n
,则out[n] += weight[i]
而不是out[n] += 1
。- 参数:
- x类数组,1 维,非负整数
输入数组。
- weights类数组,可选
权重,与 x 形状相同的数组。
- minlength整型,可选
输出数组的最小分箱数。
- 返回:
- out整型 ndarray
对输入数组进行分箱的结果。out 的长度等于
np.amax(x)+1
。
- 抛出:
- ValueError
如果输入不是 1 维的,或包含负值元素,或 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
输入数组需要是整数数据类型(dtype),否则会抛出 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])