在Numpy 1.16版本中,您可以使用histogram_bin_edges
。使用此功能,今天的解决方案调用histogram_bin_edges
来获取bin,将-inf和+inf连接起来,并将其作为bin传递给histogram
:
a=[1,2,3,4,2,3,4,7,4,6,7,5,4,3,2,3]
np.histogram(a, bins=np.concatenate(([np.NINF], np.histogram_bin_edges(a), [np.PINF])))
结果为:
(array([0, 1, 3, 0, 4, 0, 4, 1, 0, 1, 0, 2]),
array([-inf, 1. , 1.6, 2.2, 2.8, 3.4, 4. , 4.6, 5.2, 5.8, 6.4, 7. , inf]))
如果你喜欢让最后一个 bin 为空(就像我一样),你可以使用 range
参数并在 max
上加上一个小数:
a=[1,2,3,4,2,3,4,7,4,6,7,5,4,3,2,3]
np.histogram(a, bins=np.concatenate(([np.NINF], np.histogram_bin_edges(a, range=(np.min(a), np.max(a)+.1)), [np.PINF])))
结果为:
(array([0, 1, 3, 0, 4, 4, 0, 1, 0, 1, 2, 0]),
array([-inf, 1. , 1.61, 2.22, 2.83, 3.44, 4.05, 4.66, 5.27, 5.88, 6.49, 7.1 , inf]))
plt
),尽管它在内部使用numpy的hist
函数,但它不接受inf
(绘制无限的柱状图可能太多了吧?:-))。但对于我的情况来说,一个非常大的值(相对于我的数据的典型范围)效果很好。 - Josiah Yoder