排除 numpy.histogram 中的最右边缘

Excluding rightmost edge in numpy.histogram

我有一个数字列表 a 和一个 bin 列表,我将使用它们 使用 [=14= 对 a 中的数字进行分类].这些 bin 是根据 a 均值 标准差 (std) 计算的。所以bin的数量是B,第一个bin的最小值是mean - std,最后一个bin的最大值是mean + std。 (粗体中的文字表示我的最终目标)

示例如下:

>>> a
array([1, 1, 3, 2, 2, 6])

>>> bins = np.linspace(mean - std, mean + std, B + 1)
array([ 0.79217487,  1.93072496,  3.06927504,  4.20782513]))

>>> numpy.histogram(a, bins = bins)[0]
(array([2, 3, 0], dtype=int32)

但是,我想排除最后一个 bin 的最右边 - 即如果 a 中的某个值正好等于 mean + std,我不希望将它包含在最后一个 bin 中。关于 meanstd 的漫画并不重要,不包括最右边的边缘(也就是使它成为半开间隔)。 doc 说,不幸的是在这方面:

All but the last (righthand-most) bin is half-open. In other words, if bins is:

[1, 2, 3, 4] then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4.

有没有我可以采用的简单解决方案?也就是说,一种不涉及手动固定边缘的方法。这是我能做的,但这不是我想要的。有没有我可以传递的标志或我可以使用的不同方法?

这是一种(有点粗糙?)将最后一个垃圾箱半开而不是关闭的方法。我正在做的是从最右边的 bin 的右边减去可能的最小值:

a = np.array([1, 1, 3, 2, 2, 6])
B = 3 # (in this example) 
bins = np.linspace(a.mean() - a.std(), a.mean() + a.std(), B + 1)
# array([ 0.79217487,  1.93072496,  3.06927504,  4.20782513]))
bins[-1] -= np.finfo(float).eps # <== this is the crucial line
np.histogram(a, bins = bins)

如果您对 a 中的值使用 float 以外的其他类型,请在对 finfo 的调用中使用不同的类型。例如:

np.finfo(float).eps
np.finfo(np.float128).eps