Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy check if 2D array is subset of 2D array [duplicate]

I would like to check if the array b is a subset of the array a. By subset I mean I would like to check if all the elements of b are found in a.

Here is the code I have:

import numpy as np
a = np.array([[1,7,9],[8,3,12],[101,-74,0.5]])
b = np.array([[1,9],[8,12],[101,0.5]])
print a
print b

Here is the output

Array a

[[   1.     7.     9. ]
 [   8.     3.    12. ]
 [ 101.   -74.     0.5]]

Array b

[[   1.     9. ]
 [   8.    12. ]
 [ 101.     0.5]]

Is there a way to check if b is a subset of a?

EDIT: Additional Information:

As per comments below, I should clarify that I need to know if array b is a subset of array a - if even one element is missing from the subset, then I am looking for a way to check for this. I do not need to have an indication of where in the subset the element is missing but just to know it is missing. If additional information can be provided about the missing element then that will be a bonus but it is not a hard requirement. Apologies for not clearing this up earlier.

My reasoning in phrasing the question as a subset is that if one array is a subset of the other array then this would imply to me that all the values of the subset array are present in the larger array.

like image 286
edesz Avatar asked Dec 12 '25 08:12

edesz


1 Answers

I think you want numpy.in1d, something like this:

import numpy as np
a = np.array([[1,7,9],[8,3,12],[101,-74,0.5]])
b = np.array([[1,9],[8,12],[101,0.5]])

np.in1d(b.ravel(), a.ravel()).all()
like image 77
Bi Rico Avatar answered Dec 15 '25 12:12

Bi Rico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!