如何简单地设置numpy直方图的替代不等式条件?

时间:2018-10-11 12:37:38

标签: python python-3.x numpy histogram inequality

根据example in the numpy documentation

>>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]))

1看,我们注意到第二个bin中有两次出现,这意味着这些bin被视为在left <= x_i < right范围内。假设有人要切换为left < x_i <= right。是否有简单的方法可以在numpy中做到这一点?

1 个答案:

答案 0 :(得分:1)

np.histogram()使用np.searchsorted(..., side='right')计算每个样本值的仓号。因此,您可以这样做:

import numpy as np

data = [1, 2, 1]
bins = [0, 1, 2, 3]

hist = np.zeros(len(bins) - 1, dtype=int)
bin_numbers = np.searchsorted(bins, data, side='left')
for idx, val in zip(*np.unique(bin_numbers, return_counts=True)):
    hist[idx - 1] = val

result = hist, bins

result是:

(array([2, 1, 0]), [0, 1, 2, 3])