Try numpy.searchsorted
:
>> a = np.array([0, 1, 2, 3, 4, 5, 6, 7])
>> b = np.array([1, 2, 4, 3, 1, 0, 2, 9])
% sorting b "into" a
>> np.searchsorted(a, b, side='right')-1
array([1, 2, 4, 3, 1, 0, 2, 9])
您可能需要对 b 中超出 a 范围的值进行一些特殊处理 - 例如上例中的 9。
尽管如此,这应该比任何基于循环的方法更快。
作为旁白:
相似地,histc
在 MATLAB 中会比循环快得多。
EDIT:
如果你想得到索引在哪里b
最接近a
,您应该能够使用相同的代码,只需修改一下 a:
>> a_mod = 0.5*(a[:-1] + a[1:]) % take the centers between the elements in a
>> np.searchsorted(a_mod, np.array([0.9, 2.1, 4.2, 2.9, 1.1]), side='right')
array([1, 2, 4, 3, 1])
请注意,您可以删除-1
since a_mod
有一个元素小于a
.