Python 的 numpy 模块提供了一个名为 numpy.histogram() 的函数。此函数表示与一组值范围进行比较的值数量的频率。这个函数类似于matplotlib.pyplot的hist()函数。
简单来说,这个函数用于计算数据集的直方图。
用法:
numpy.histogram(x, bins=10, range=None, normed=None, weights=None, density=None)
参数:
x:数组
此参数定义了一个扁平化的数组,在该数组上计算直方图。
bins:int 或 str 或标量序列(可选)
如果此参数定义为整数,则在给定范围内,它定义了 equal-width 个 bin 的数量。否则,定义单调增加的 bin 边数组。它还包括最右边的边,允许不均匀的 bin 宽度。最新版本的 numpy 允许我们将 bin 参数设置为字符串,它定义了一种计算最佳 bin 宽度的方法。
范围:(浮点数,浮点数)(可选)
该参数定义了 bin 的 lower-upper 范围。默认情况下,范围是 (x.min(), x.max())。超出范围的值将被忽略。第一个元素的范围应该等于或小于第二个元素。
规范:布尔(可选)
此参数与密度参数相同,但它可能会为不相等的 bin 宽度提供错误的输出。
权重:数组(可选)
该参数定义了一个包含权重且形状与 'x' 相同的数组。
密度:布尔(可选)
如果设置为 True,将导致每个 bin 中的样本数。如果其值为 False,则密度函数将导致 bin 中概率密度函数的值。
返回值:
历史:数组
密度函数返回直方图的值。
edge_bin:浮点型数组
此函数返回 bin 边 (length(hist+1))。
范例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]))
在上面的代码中
- 我们已经导入了别名为 np.
- 我们已经声明了变量 'a' 并分配了 np.histogram() 函数的返回值。
- 我们在函数中传递了一个数组和 bin 的值。
- 最后,我们尝试打印 'a' 的值。
在输出中,它显示了一个包含直方图值的 ndarray。
范例2:
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]))
范例3:
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]))
范例4:
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. ])
范例5:
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
在上面的代码中
- 我们已经导入了别名为 np.
- 我们使用 np.arange() 函数创建了一个数组 'a'。
- 我们已经声明了变量 'hist' 和 'bin_edges',然后分配了 np.histogram() 函数的返回值。
- 我们已经传递了数组 'a' 并在函数中将 'density' 设置为 True。
- 我们尝试打印 'hist' 的值。
- 最后,我们尝试使用 hist.sum() 和 np.sum() 计算直方图值的总和,其中我们传递了直方图值和 bin 的边。
在输出中,它显示了一个包含直方图值和直方图值总和的 ndarray。
相关用法
- Python numpy.hypot()用法及代码示例
- Python numpy.hsplit()用法及代码示例
- Python numpy.hstack()用法及代码示例
- Python numpy.less()用法及代码示例
- Python numpy.tril()用法及代码示例
- Python numpy.fromstring()用法及代码示例
- Python numpy.random.standard_normal()用法及代码示例
- Python numpy.lookfor()用法及代码示例
- Python numpy.nonzero()用法及代码示例
- Python numpy.maximum_sctype()用法及代码示例
- Python numpy.ma.make_mask_none()用法及代码示例
- Python numpy.mean()用法及代码示例
- Python numpy.nancumsum()用法及代码示例
- Python numpy.atleast_2d()用法及代码示例
- Python numpy.isreal()用法及代码示例
- Python numpy.place()用法及代码示例
- Python numpy.invert()用法及代码示例
- Python numpy.polymul()用法及代码示例
- Python numpy.partition()用法及代码示例
- Python numpy.angle()用法及代码示例
注:本文由纯净天空筛选整理自 numpy.histogram() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。