np.histogram:numpy historgam()在Python中是如何工作的

1,186 阅读3分钟

np.histogram - How does numpy historgam() works in Python

np.histogram()是一个numpy 库函数,它返回一个数组,可用于在图形中绘制。该数组是根据传递的参数创建的。np.histogram() 函数为函数中给出的数据计算直方图。它可以用于探索数据。这个数组可以被绘制在图表中,以方便理解数据。

语法

numpy.histogram(arr, bins=10, range=None, normed=None, weights=None, density=None)

参数

np.histogram() 函数需要一个必要参数作为参数,并有五个可选参数。

  1. arr:数组在这个参数中被传递。这个数组是返回直方图的必要参数。要给直方图函数的数组在这个参数中显示。
  2. bins: 它是bin的数量。10被保留为默认的bins。这个bin的值可以是一串数字或int或str。如果是int,那么bin的宽度将被平均创建。如果它是一个列表,那么bin的值就会改变。
  3. 范围:这是一个范围,在这个范围内的值将被考虑。如果数值超过了这个范围,那么这个数值将不会被考虑。这个范围由两个值组成,开始和结束。这被包含在一个元组中。这个元组由( start, end )范围内的开始和结束值组成。
  4. normed:这与密度参数类似。
  5. 权重:这个参数是用一个由权重组成的数组传递的。这个权重数组的形状应该等于数组a的形状。如果密度参数被设置为True ,这些权重将被规范化。
  6. 密度:如果是True,那么它就是一个概率密度函数的值。如果是False,那么数组将有每个bin中存在的样本数。

返回值

它返回两个值。一个是由直方图值组成的数组,另一个是由bin边缘组成的数组。

使用 np.histogram() 返回直方图数组的 Python 程序

# Importing numpy as np
import numpy as np

# Creating a numpy array called arr
arr = np.array([5, 3, 7, 8, 1, 9, 2])
print("The array is : ", arr)

# Printing the shape of the array using shape function
print(" Shape of the array is : ", arr.shape)
res = np.histogram(arr)
print("The Histogram array is: ", res)

输出

The array is : [5 3 7 8 1 9 2]
Shape of the array is : (7,)
The Histogram array is: (array([1, 1, 1, 0, 0, 1, 0, 1, 1, 1]), array([1. , 1.8, 2.6, 3.4, 4.2, 5. , 5.8, 6.6, 7.4, 8.2, 9. ]))/* Your code... */

在这个程序中,我们导入numpy来创建一个numpy数组。然后,我们打印了这个数组,并使用np.shape 打印了这个数组的形状。

在下一步中,我们将这个数组传入np.histogram() 函数。np.histogram() 函数返回两个值,一个是由直方图值组成的数组,另一个是bin的边缘值。

使用np.histogram()返回随机数的直方图数组的Python程序

# Importing numpy as np
import numpy as np

# Creating a numpy array called arr
arr = np.random.randint(70, size=(40))
print("The array is : ", arr)

# Printing the shape of the array using shape function
print(" Shape of the array is : ", arr.shape)
res = np.histogram(arr, bins=[0, 10, 20, 30, 40, 50], range=(0, 50))
print("The Histogram array is: ", res)

输出

The array is : [41 19 64 35 10 60 56 56 6 28 37 61 8 4 39 45 29 3 5 19 24 28 57 10
30 46 51 30 16 40 57 64 54 68 37 30 2 41 41 12]
Shape of the array is : (40,)
The Histogram array is: (array([6, 6, 4, 7, 6]), array([ 0, 10, 20, 30, 40, 50]))

在这个程序中,我们传递了bins和range的值。range() 函数删除了大于和小于指定范围的值。只有在指定范围内的值才会被考虑。

本教程就到此为止。