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

后端 未结 8 1034
旧巷少年郎
旧巷少年郎 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]
    

提交回复
热议问题