numpy.
bincount
计数非负整数数组中每个值的出现次数。
箱数(1号)大于 x .如果 minlength 如果指定,则输出数组中至少会有此数量的存储桶(但如果需要,它将更长,具体取决于 x )每个bin给出其索引值的出现次数 x .如果 weights 指定输入数组的权重,即如果一个值 n 在位置处找到 i , out[n] += weight[i] 而不是 out[n] += 1 .
n
i
out[n] += weight[i]
out[n] += 1
输入数组。
权重,形状与相同的数组 x .
输出数组的最小箱数。
1.6.0 新版功能.
对输入数组进行分块的结果。长度 out 等于 np.amax(x)+1 .
np.amax(x)+1
如果输入不是一维的,或者包含负值的元素,或者如果 minlength 是否定的。
如果输入的类型是float或complex。
参见
histogram
digitize
unique
实例
>>> 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
输入数组必须是整数数据类型,否则将引发类型错误:
>>> 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 关键字。
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])