原文:https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html
校对:(虚位以待)
numpy.
bincount
(x, weights=None, minlength=None)计算非负整数数组中每个值的出现次数。
块(大小为1)的数量大于x中的最大值。如果指定minlength,那么在输出数组中至少会有这个数目的bin(如果需要,根据x的内容,它会更长)。每个bin给出其索引值在x中的出现次数。If weights is specified the input array is weighted by it, i.e. if a value n
is found at position i
, out[n] += weight[i]
instead of out[n] += 1
.
参数: | x:array_like,1 dimension,nonnegative ints
权重:array_like,可选
minlength:int,可选
|
---|---|
返回: | out:intar的ndarray
|
上升: | ValueError
TypeError
|
例子
>>> 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=np.float))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: array cannot be safely cast to required type
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])