如何 "bin" 使用自定义(非线性间隔)桶的 numpy 数组?

How to "bin" a numpy array using custom (non-linearly spaced) buckets?

如何 "bin" numpy 中的波纹管数组,以便:

import numpy as np
bins = np.array([-0.1 , -0.07, -0.02,  0.  ,  0.02,  0.07,  0.1 ])
array = np.array([-0.21950869, -0.02854823,  0.22329239, -0.28073936, -0.15926265,
              -0.43688216,  0.03600587, -0.05101109, -0.24318651, -0.06727875])

即将 array 中的每个 values 替换为以下内容:

-0.1 where `value` < -0.085
-0.07 where -0.085 <= `value` < -0.045
-0.02 where -0.045 <= `value` < -0.01
0.0 where -0.01 <= `value` < 0.01
0.02 where 0.01 <= `value` < 0.045
0.07 where 0.045 <= `value` < 0.085
0.1 where `value` >= 0.085

预期输出为:

array = np.array([-0.1, -0.02,  0.1, -0.1, -0.1, -0.1,  0.02, -0.07, -0.1, -0.07])

我知道 numpy 有一个 digitize 函数,但是它 returns bin 的索引而不是 bin 本身。即:

np.digitize(array, bins)
np.array([0, 2, 7, 0, 0, 0, 5, 2, 0, 2])

通过对连续的 bin 值成对求平均值来获取这些中间值。然后,使用 np.searchsortednp.digitize 使用中间值获取索引。最后,为输出索引 bins

中间值:

mid_bins = (bins[1:] + bins[:-1])/2.0

索引 searchsorteddigitze :

idx = np.searchsorted(mid_bins, array)
idx = np.digitize(array, mid_bins)

输出:

out = bins[idx]