在我的Python脚本中,我有浮动,我想要bin。现在我正在做:
min_val = 0.0
max_val = 1.0
num_bins = 20
my_bins = numpy.linspace(min_val, max_val, num_bins)
hist,my_bins = numpy.histogram(myValues, bins=my_bins)
但现在我想再添加两个箱来解释<0.0的值和> 1.0的值。因此,一个bin应该包括(-inf,0)中的所有值,另一个包含在[1,inf)中
在使用numpy的histogram
函数时,有没有直接的方法呢?
函数numpy.histogram()
在bins
参数中愉快地接受无限值:
numpy.histogram(my_values, bins=numpy.r_[-numpy.inf, my_bins, numpy.inf])
或者,您可以使用numpy.searchsorted()
和numpy.bincount()
的组合,但我认为这种方法没有太大的优势。
您可以将numpy.inf
指定为upper,将-numpy.inf
指定为较低的bin限制。
使用Numpy版本1.16,你有histogram_bin_edges
。有了这个,今天的解决方案调用histogram_bin_edges
来获取垃圾箱,concatenate
-inf和+ inf并将其作为垃圾箱传递给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]))