Python 使用NumPy计算数据集的直方图

Python 使用NumPy计算数据集的直方图

直方图是数据集分布的图形表示。它以一系列柱状图的形式表示数据,其中每个柱的数据值范围表示每个柱中定义的数据值的频率。

主要用于表示数值数据的分布,如一个班级的成绩、人口分布或员工收入分布。

在直方图中,x轴表示数据值的范围,分为若干区间,y轴表示每个区间内的数据值的频率。直方图可以通过将每个区间的频率除以总数据值来归一化,得到相对频率直方图,其中y轴表示每个区间的数据值。

使用Python Numpy计算直方图

Python中,用于创建直方图的有numpy、matplotlib和seaborn库。在Numpy中,我们有一个名为histogram()的函数来处理直方图数据。

语法

以下是创建给定数据范围的直方图的语法。

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

在下面的示例中,我们使用Numpy的histogram()函数创建了一个直方图。在这里,我们将一个数组作为输入参数,将bins定义为10,这样直方图将以10个bins创建,其余参数可以保持为none。

import numpy as np
arr = np.array([10,20,25,40,35,23])
hist = np.histogram(arr,bins = 10)
print("The histogram created:",hist)

输出

The histogram created: (array([1, 0, 0, 1, 1, 1, 0, 0, 1, 1], dtype=int64), array([10., 13., 16., 19., 22., 25., 28., 31., 34., 37., 40.]))

示例

让我们看一个示例来理解numpy库的histogram()函数。

import numpy as np
arr = np.array([[20,20,25],[40,35,23],[34,22,1]])
hist = np.histogram(arr,bins = 20)
print("The histogram created:",hist)

输出

The histogram created: (array([1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 0, 0, 0,
1, 1, 0, 1],
 dtype=int64), array([ 1. , 2.95, 4.9 , 6.85, 8.8 , 10.75, 12.7 ,
14.65, 16.6 ,
 18.55, 20.5 , 22.45, 24.4 , 26.35, 28.3 , 30.25, 32.2 , 34.15,
 36.1 , 38.05, 40. ]))  

示例

在本例中,我们通过指定柱状图的区间和数据范围来创建一个直方图。以下代码可作为参考。

import numpy as np
arr = np.array([[20,20,25],[40,35,23],[34,22,1]])
hist = np.histogram(arr,bins = 20, range = (1,10))
print("The histogram created:", hist)

输出

The histogram created: (array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0],
 dtype=int64), array([ 1. , 1.45, 1.9 , 2.35, 2.8 , 3.25, 3.7 ,4.15, 4.6 ,
 5.05, 5.5 , 5.95, 6.4 , 6.85, 7.3 , 7.75, 8.2 , 8.65,
 9.1 , 9.55, 10. ]))

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程