使用Python中的NumPy计算一组数据的直方图

WBOY
WBOY 转载
2023-08-28 20:01:15 923浏览

使用Python中的NumPy计算一组数据的直方图

直方图是数据集分布的图形表示。它以一系列的条形图的形式表示数据,其中每个条形图代表的数据值范围,条形图的高度代表在该范围内定义的数据值的频率。

这些主要用于表示数值数据的分布,如班级中的成绩分布,人口分布或员工收入分布等。

In histogram, x-axis represents the range of data values, divided into intervals and the y-axis represents the frequency of the range of data values within each bin. Histograms can be normalized by dividing the frequency of each bin by the total data values, which results to the relative frequency histogram where y-axis represents the data values of each bin.

Calculating histogram using Python Numpy

In python, for creating the histograms we have numpy, matplotlib and seaborn libraries. In Numpy, we have the function named histogram() to work with the histogram data.

语法

Following is the syntax for creating the histograms for the given range of data.

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

Where,

的中文翻译为:

在哪里,

  • arr 是输入数组

  • bins 是用来表示数据的柱状图中的条形数量

  • range 定义了直方图中的值的范围

  • normed 偏好密度参数

  • weights是可选参数,用于每个数据值的权重

  • 密度是将直方图数据归一化为概率密度的参数。

The output of the histogram function will be a tuple containing the histogram counts and bin edges.

Example

在下面的示例中,我们使用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)

Output

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

Example

让我们看一个例子来理解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)

Output

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

Example

在这个例子中,我们通过指定bins和要使用的数据范围来创建一个直方图。以下代码可以作为参考。

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)

Output

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

以上就是使用Python中的NumPy计算一组数据的直方图的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除