Numpy: For every element in one array, find the index in another array

后端 未结 8 1032
旧巷少年郎
旧巷少年郎 2020-12-02 18:36

I have two 1D arrays, x & y, one smaller than the other. I\'m trying to find the index of every element of y in x.

I\'ve found two naive ways to do this, the fir

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 18:51

    As Joe Kington said, searchsorted() can search element very quickly. To deal with elements that are not in x, you can check the searched result with original y, and create a masked array:

    import numpy as np
    x = np.array([3,5,7,1,9,8,6,6])
    y = np.array([2,1,5,10,100,6])
    
    index = np.argsort(x)
    sorted_x = x[index]
    sorted_index = np.searchsorted(sorted_x, y)
    
    yindex = np.take(index, sorted_index, mode="clip")
    mask = x[yindex] != y
    
    result = np.ma.array(yindex, mask=mask)
    print result
    

    the result is:

    [-- 3 1 -- -- 6]
    

提交回复
热议问题