Find indexes of matching rows in two 2-D arrays

前端 未结 3 1669
广开言路
广开言路 2021-02-13 18:36

Suppose that I have two 2-D arrays as follows:

array([[3, 3, 1, 0],
       [2, 3, 1, 3],
       [0, 2, 3, 1],
       [1, 0, 2, 3],
       [3, 1, 0, 2]], dtype=in         


        
3条回答
  •  别那么骄傲
    2021-02-13 19:03

    This is an all numpy solution - not that is necessarily better than an iterative Python one. It still has to look at all combinations.

    In [53]: np.array(np.all((x[:,None,:]==y[None,:,:]),axis=-1).nonzero()).T.tolist()
    Out[53]: [[0, 4], [2, 1], [3, 2], [4, 3]]
    

    The intermediate array is (5,5,4). The np.all reduces it to:

    array([[False, False, False, False,  True],
           [False, False, False, False, False],
           [False,  True, False, False, False],
           [False, False,  True, False, False],
           [False, False, False,  True, False]], dtype=bool)
    

    The rest is just extracting the indices where this is True

    In crude tests, this times at 47.8 us; the other answer with the L1 dictionary at 38.3 us; and a third with a double loop at 496 us.

提交回复
热议问题