问题
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