Home > Back-end >  different element between two 2D numpy arrays
different element between two 2D numpy arrays

Time:06-09

I have two 2D numpy arrays.

arr1 = np.array([[1,4], [3,4], [5,4]])
arr2 = np.array([[1,3], [3,4], [4,5], [5,6]])

I'd like to get the elements (axis 0) in arr1 which don't exist in arr2, the order matters.

So the wanted result is:

np.array([[1,4], [5,4]])

Any idea will be appreciated.

CodePudding user response:

You can use broadcasting with all/any comparison:

arr1[(arr1[:,None]!=arr2).any(2).all(1)]

output:

array([[1, 4],
       [5, 4]])

intermediates:

(arr1[:,None]!=arr2)

array([[[False,  True],
        [ True, False],
        [ True,  True],
        [ True,  True]],

       [[ True,  True],
        [False, False],
        [ True,  True],
        [ True,  True]],

       [[ True,  True],
        [ True, False],
        [ True,  True],
        [False,  True]]])

# at least one True (any) means different
(arr1[:,None]!=arr2).any(2)

array([[ True,  True,  True,  True],
       [ True, False,  True,  True],
       [ True,  True,  True,  True]])
​
# all other subarrays are different (all)
(arr1[:,None]!=arr2).any(2).all(1)

array([ True, False,  True])

CodePudding user response:

You could use a list comprehension:

print([x for x in arr1 if not x.tolist() in arr2.tolist()])
  • Related