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

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

    A more direct solution, that doesn't expect the array to be sorted.

    import pandas as pd
    A = pd.Series(['amsterdam', 'delhi', 'chromepet', 'tokyo', 'others'])
    B = pd.Series(['chromepet', 'tokyo', 'tokyo', 'delhi', 'others'])
    
    # Find index position of B's items in A
    B.map(lambda x: np.where(A==x)[0][0]).tolist()
    

    Result is:

    [2, 3, 3, 1, 4]
    
    0 讨论(0)
  • 2020-12-02 19:05

    I think this is a clearer version:

    np.where(y.reshape(y.size, 1) == x)[1]
    

    than indices = np.where(y[:, None] == x[None, :])[1]. You don't need to broadcast x into 2D.

    This type of solution I found to be best because unlike searchsorted() or in1d() based solutions that have seen posted here or elsewhere, the above works with duplicates and it doesn't care if anything is sorted. This was important to me because I wanted x to be in a particular custom order.

    0 讨论(0)
提交回复
热议问题