Index mapping between two sorted partially overlapping numpy arrays

烂漫一生 提交于 2020-01-11 13:27:28

问题


I want to solve something like the problem detailed at Find index mapping between two numpy arrays, but where the two arrays do not necessarily contain the same set of values, although their values are unique within each array, and are sorted.

E.g. if I have two arrays:

a = np.array([1.1, 2.2, 3.3, 4.4, 5.5])
b = np.array([2.2, 3.0, 4.4, 6.0])

I want to get an array of the same length as a which gives the index into b where the matching element is, or -1 if there is no match. I.e. in this case:

map = np.array([-1, 0, -1, 2, -1])

Is there a neat, fast way to do this using np.searchsorted?


回答1:


Use the searchsorted indices to do a check on matches and then mask the invalid ones with the invalid-specifier. For the matching check, do b[idx]==a with idx as those indices. Hence -

invalid_specifier = -1
idx = np.searchsorted(b,a)
idx[idx==len(b)] = 0
out = np.where(b[idx]==a, idx, invalid_specifier)


来源:https://stackoverflow.com/questions/57873670/index-mapping-between-two-sorted-partially-overlapping-numpy-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!