Python的numpy模块提供了一个名为 numpy.histogram()的函数。该函数表示与一组值范围进行比较的值的数量的频率。此函数类似于 matplotlib.pyplot 的 hist()函数。
简而言之,此函数用于计算数据集的直方图。
numpy.histogram(x, bins=10, range=None, normed=None, weights=None, density=None)
x:array_like
此参数定义一个扁平数组,在该数组上可以计算直方图。
bins:int或str或scalars(可选)
如果将此参数定义为整数,则在给定范围内,它将定义等宽bin的数量。否则,定义了单调增加的仓边阵列。它还包括最右边,允许不均匀的料槽宽度。 numpy 的最新版本允许我们将bin参数设置为字符串,该字符串定义了一种用于计算最佳bin宽度的方法。
range:(float,float)(可选)
此参数定义上下部范围。默认情况下,范围是(x.min(),x.max())。这些值将被忽略,超出范围。第一个元素的范围应等于或小于第二个元素。
normed:bool(可选)
此参数与density参数相同,但是对于不等的箱宽,它会给出错误的输出。
weights:array_like(可选)
此参数定义一个包含权重且形状与'x'相同的数组。
density:bool(可选)
如果将其设置为True,将导致每个bin中的样本数量。如果其值为False,则密度函数将得出分箱中概率密度函数的值。
hist:array
密度函数返回直方图的值。
edge_bin:float dtype数组
此函数返回仓边缘(length(hist + 1))。
import numpy as np a=np.histogram([1, 5, 2], bins=[0, 1, 2, 3]) a
输出:
(array([0, 1, 1], dtype=int64), array([0, 1, 2, 3]))
在上面的代码中
在输出中,它显示了包含直方图值的ndarray。
import numpy as np x=np.histogram(np.arange(6), bins=np.arange(7), density=True) x
输出:
(array([0.16666667, 0.16666667, 0.16666667, 0.16666667, 0.16666667, 0.16666667]), array([0, 1, 2, 3, 4, 5, 6]))
import numpy as np x=np.histogram([[1, 3, 1], [1, 3, 1]], bins=[0,1,2,3]) x
输出:
(array([0, 4, 2], dtype=int64), array([0, 1, 2, 3]))
import numpy as np a = np.arange(8) hist, bin_edges = np.histogram(a, density=True) hist bin_edges
输出:
array([0.17857143, 0.17857143, 0.17857143, 0. , 0.17857143, 0.17857143, 0. , 0.17857143, 0.17857143, 0.17857143]) array([0. , 0.7, 1.4, 2.1, 2.8, 3.5, 4.2, 4.9, 5.6, 6.3, 7. ])
import numpy as np a = np.arange(8) hist, bin_edges = np.histogram(a, density=True) hist hist.sum() np.sum(hist * np.diff(bin_edges))
输出:
array([0.17857143, 0.17857143, 0.17857143, 0. , 0.17857143, 0.17857143, 0. , 0.17857143, 0.17857143, 0.17857143]) 1.4285714285714288 1.0
在上面的代码中
在输出中,它显示了一个ndarray,其中包含直方图的值和直方图值的总和。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)