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

Numpy : check if any array in 3D array is in another shorter 3D array with duplicates

I’ve got a Numpy array like this one :

source = np.array([[[0,0,0],[0,0,1],[0,1,0],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]])

And I’m trying to compare it to an other array, which has shorter Axis2 and duplicates in Axis3 :

values = np.array([[[0,1,0],[1,0,0],[1,1,1],[1,1,1],[0,1,0]]])

My goal is to have an array of booleans as long as the longest :

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

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

I’ve tried these command :

np.isin(source,values).all(axis=2)

But it displays an array of seven True. A function like numpy.in1d() seemed to be a good option, but I’ve didn’t achieve to adapt it for 3D arrays.

>Solution :

One way:

np.in1d(np.apply_along_axis(''.join, 2, source.astype(str)), 
        np.apply_along_axis(''.join, 2, values.astype(str)))

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

Another way, though might be memory intensive:

(source.transpose(1,0,2) == values).all(2).any(1)
array([False, False,  True,  True, False, 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