Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Any idea will be appreciated.

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading