Check whether each row of a matrix is in another matrix [Python]

前端 未结 1 723
面向向阳花
面向向阳花 2021-01-25 06:36

I have two matrices (or, better, 2D numpy arrays), A and B, with same number of columns (well, to be fair they have a different number of rows, however

相关标签:
1条回答
  • 2021-01-25 07:09

    You can use a vectorized approach using NumPy broadcasting, like so -

    np.argwhere((B[:,None,[0,1]] == A[:,[1,2]]).all(-1))
    

    Alternatively, since you are dealing with rows of just 2 elements, a memory efficient approach that stays 2D could be suggested, like so -

    np.argwhere((B[:,None,0] == A[:,1]) & (B[:,None,1] == A[:,2]))
    

    The output would be (N,2) shaped array, in which the first column gives us the row indices of B and the second column of A corresponding to matches across all elements in a row.

    Sample run -

    In [154]: A[:,[1,2]]
    Out[154]: 
    array([[0, 1],
           [0, 2],
           [2, 1],
           [1, 2],
           [0, 1]])
    
    In [155]: B[:,[0,1]]
    Out[155]: 
    array([[0, 1],
           [2, 2],
           [1, 2],
           [0, 2],
           [2, 1],
           [2, 1],
           [1, 0]])
    
    In [156]: np.argwhere((B[:,None,[0,1]] == A[:,[1,2]]).all(-1))
    Out[156]: 
    array([[0, 0],
           [0, 4],
           [2, 3],
           [3, 1],
           [4, 2],
           [5, 2]])
    
    0 讨论(0)
提交回复
热议问题