numpy.bincount使用方法介绍

参考文章:https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html

numpy. bincount ( xweights=Noneminlength=0 )

统计非负整数出现的次数。每一个bin都是给出输入数组中每一个数出现的次数。如果有加权的w值,输出是out[n] += weight[i],而不是out[n] +=1。

Parameters:

x : 输入数组

weights : 加权,和x的shape一致

minlength : 输出矩阵bin数的最小值

Returns:

out : 输入矩阵分bin的结果。输出矩阵长度:输入矩阵最大值+1 = np.amax(x)+1

Raises:

值错误:

如果输入不是1维,或者元素有负数,则错误

类型错误:

如果输入类型为float浮点或者complex复数,这错误


示例:

1、统计每个元素出现次数

>>> 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])


2、输出数组长度

>>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
>>> np.bincount(x).size == np.amax(x)+1
True


3、输入数据类型要为整数

>>> np.bincount(np.arange(5, dtype=float))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: array cannot be safely cast to required type


4、有权值w,则计算输出时,累加x值对应位置的w值

>>> 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])


猜你喜欢

转载自blog.csdn.net/weixin_41770169/article/details/80715092