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

后端 未结 8 1098
旧巷少年郎
旧巷少年郎 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:42

    How about this?

    It does assume that every element of y is in x, (and will return results even for elements that aren't!) but it is much faster.

    import numpy as np
    
    # Generate some example data...
    x = np.arange(1000)
    np.random.shuffle(x)
    y = np.arange(100)
    
    # Actually preform the operation...
    xsorted = np.argsort(x)
    ypos = np.searchsorted(x[xsorted], y)
    indices = xsorted[ypos]
    

提交回复
热议问题