W R W R - 6 months ago 37
Python Question

NumPy check if 2D array is subset of 2D array

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?

Answer

This should work:

set(np.unique(b)).issubset(set(np.unique(a)))