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