check for identical rows in different numpy arrays

后端 未结 6 815
无人共我
无人共我 2020-11-28 15:14

how do I get a row-wise comparison between two arrays, in the result of a row-wise true/false array?

Given datas:

a = np.array([[1,0],[2,0],[3,1],[         


        
6条回答
  •  旧时难觅i
    2020-11-28 16:13

    a = np.array([[1,0],[2,0],[3,1],[4,2]])
    b = np.array([[1,0],[2,0],[4,2]])
    
    i = 0
    j = 0
    result = []
    

    We can take advantage of the fact that they are sorted and do this in O(n) time. Using two pointers we just move ahead the pointer that has gotten behind:

    while i < len(a) and j < len(b):
        if tuple(a[i])== tuple(b[j]):
            result.append(True)
            i += 1
            j += 1 # get rid of this depending on how you want to handle duplicates
        elif tuple(a[i]) > tuple(b[j]):
            j += 1
        else:
            result.append(False)
            i += 1
    

    Pad with False if it ends early.

    if len(result) < len(a):
        result.extend([False] * (len(a) - len(result)))
    
    print(result) # [True, True, False, True]
    

    This answer is adapted from Better way to find matches in two sorted lists than using for loops? (Java)

提交回复
热议问题