np.histogram()直方图分布

np.histogram()是一个生成直方图的函数

>>>d = np.random.laplace(loc=15, scale=3, size=500)
>>>> d[:10]
array([13.88469924, 14.39847862, 19.09746795, 17.36852791, 22.84303082,
       20.13163875, 13.83920361, 14.64293351, 13.83945571, 14.05509207])
>>> np.histogram(d)
(array([  1,   0,   0,   2,   6,  45, 242, 179,  20,   5], dtype=int64), array([-20.31921637, -15.19140308, -10.06358978,  -4.93577649,
         0.19203681,   5.3198501 ,  10.4476634 ,  15.57547669,
        20.70328999,  25.83110328,  30.95891658]))
>>> hist
array([  1,   0,   0,   2,   6,  45, 242, 179,  20,   5], dtype=int64)
>>> bin_edges
array([-20.31921637, -15.19140308, -10.06358978,  -4.93577649,
         0.19203681,   5.3198501 ,  10.4476634 ,  15.57547669,
        20.70328999,  25.83110328,  30.95891658])

这代表了[-20.31921637, -15.19140308]之间的元素有1个;[-15.19140308, -10.06358978]之间的元素有0个…[25.83110328, 30.95891658]之间的元素有5个

np.histogram() 默认地使用10个相同大小的区间(箱),然后返回一个元组(频数,分箱的边界),如上所示。要注意的是:这个边界的数量是要比分箱数多一个的,因为边界永远会比区域多一个值。可以简单通过下面代码证实。

>>> hist.size, bin_edges.size
(10, 11)

以下是其内部的具体实现

>>> # 取a的最小值和最大值
>>> first_edge, last_edge = a.min(), a.max()
>>> n_equal_bins = 10 # NumPy得默认设置,10个分箱
>>> bin_edges = np.linspace(start=first_edge, stop=last_edge,
...    num=n_equal_bins + 1, endpoint=True)
...
>>> bin_edges
array([ 0. , 2.3, 4.6, 6.9, 9.2, 11.5, 13.8, 16.1, 18.4, 20.7, 23. ])

首先获取a列表的最小值和最大值,然后设置默认的分箱数量,最后使用Numpy的 linspace 方法进行数据段分割。分箱区间的结果也正好与实际吻合,0到23均等分为10份,23/10,那么每份宽度为2.3。

你可能感兴趣的:(大数据,Python)