numpy的bincount()方法有什么用? 在一个正(+ve)整数的数组中,numpy.bincount()方法对每个元素的出现进行计数。
np.bincount
np.bincount()是numpy库中的一个方法,用于获得numpy数组内提供的每个元素的频率。numpy bincount()方法将arr_name、weights 和minlength 作为参数,并返回整数的ndarray。
要计算非负整数数组中每个值的出现次数,请使用**numpy.bincount()**函数。
数组内的所有元素必须是整数数据类型,同时,它们应该是非负数;否则,会产生一个TypeError。元素的计数被存储为其在频率数组/bin中的索引。
因此,我们可以得出结论,每个bin值对应于其索引的出现。因此,我们可以相应地设置bin的大小。仓的大小将总是等于给定数组中最大的数字+1。
例如:如果数组是[1,6,6,4,2,8,5],那么仓的大小将是9,因为8是数组中最大的元素。 如果提供了权重数组,那么输入的数组就会被它加权。
语法
numpy.bincount(arr_name, weights = None, minlength=0)
参数
bincount()函数最多需要三个主要参数:
- arr_name:这是一个输入数组,其中的频率元素要被计数
- weights:一个与输入数组形状相同的附加数组
- minlength:它指定了输出数组中的最小分档数
返回值
bincount()函数返回一个ints的ndarray
输出数组由输入数组中bin的索引值的若干次出现组成
输出数组的大小是+1,大于输入数组中的最大元素
编程实例
显示numpy.bincount()工作原理的程序
# importing the numpy module
import numpy as np
# Input array of non-negative integers
inp_arr = np.array([1, 2, 5, 6, 2, 1, 8, 8, 8])
x = np.bincount(inp_arr)
print("Output of bincount is: ", x)
# printing the size of output bin
print("\nSize of output bin: ", len(x))
输出
Output of bincount is: [0 2 2 0 0 1 1 0 3]
Size of output bin: 9
解释
在程序bincount1.py中,我们使用了一个名为inp_arr的numpy数组,并在数组中存储了多个非负数元素,这些元素的频率需要被计算。
然后,我们在np.bincount()方法中把整个数组作为参数传递,并将其返回值存储在一个名为x的变量中。
之后,我们通过使用x显示新得到的bincount数组的元素来打印输出;我们可以得出的结论是,在np.bincount()中,每个bin值对应于其索引的出现。
请看下面的图片,以便更好地理解:
通过程序来理解np.bincount()方法在给定一个额外的权重数组作为参数时的工作。
请看下面的代码:
# importing the numpy module
import numpy as np
# Input array of non-negative integers
inp_arr = np.array([1, 2, 5, 6, 2, 1, 8, 8, 8])
# Weighted Array
weights = np.array([1, 1, 1, 0.5, 1, 1, 1, 1, 2])
output_bin = np.bincount(inp_arr, weights)
print("Output of bincount is: ", output_bin)
# printing the size of output bin
print("\nSize of output bin: ", len(output_bin))
输出
Output of bincount is: [0 2 2 0 0 1 1 0 3]
Size of output bin: 9
解释
在这个名为bincount2.py.的代码例子中,权重参数可以用来进行元素相加。因此,对应于索引的元素将被逐个添加。因此,在不同的索引中的元素被给定为。
索引0 对应元素=0**,** 索引1 对应元素=0, 在索引1 对应元素=1+1=2,在 索引2 对应元素=1+1=2,在 索引3 和 索引4 对应元素=0,在 索引5 对应元素=1,在 索引6 对应元素=0.5,在:索引7对应元素= 0,在 索引8,对应元素=1+1+2=4。
请看下面所示的图片,以便更好地理解:
本教程就到此为止。