numpy.bincount#

numpy.bincount(x, /, weights=None, minlength=0)#

计算非负整数数组中每个值的出现次数.

箱的数量(大小为 1)比 x 中的最大值大 1.如果指定了 minlength ,则输出数组中将至少有此数量的箱(但如有必要,根据 x 的内容,它会更长).每个箱给出其索引值在 x 中出现的次数.如果指定了 weights ,则输入数组会通过它进行加权,即如果值“n”在位置“i”找到,则“out[n] += weight[i]”而不是“out[n] += 1”.

参数:
x类数组, 1 维, 非负整数

输入数组.

weightsarray_like, optional

权重,与 x 形状相同的数组.

minlength整数,可选

输出数组的最小 bin(箱)的数量.

返回:
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])