pnina
pnina

Reputation: 119

different element between two 2D numpy arrays

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]])

Upvotes: 1

Views: 43

Answers (2)

Spok
Spok

Reputation: 391

You could use a list comprehension:

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

Upvotes: 0

mozway
mozway

Reputation: 260480

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])

Upvotes: 1

Related Questions