How To Check If A Numpy Array Is A Subarray Of Another Bigger Array
So basically I have two arrays, and I want to check if one array is in another... I'm looking for a way to do something like this: >>> arr1 = np.array([1, 0, 0, 1, 1, 0])
Solution 1:
The most intuitive way seems to be an iterative process like so:
defisSubset(arr1, arr2):
m = len(arr1)
n = len(arr2)
for i inrange(0, n):
for j inrange(0, m):
if arr2[i] == arr1[j]
break;
"""
If the above inner loop was
not broken at all then arr2[i]
is not present in arr1
"""if j == m:
returnFalse"""
If we reach here then all
elements of arr2 are present
in arr1
"""returnTrue
Solution 2:
try using a 2D mask:
ix = np.arange(len(arr1) - len(test_array))[:,None] + np.arange(len(test_array))
(arr1[ix] - test_array).all(axis=1).any()
>> False
(arr2[ix] - test_array).all(axis=1).any()
>> True
or in a function:
defarray_in(arr, test_arr):
return (arr[np.arange(len(arr) - len(test_arr))[:,None] +
np.arange(len(test_arr))] == test_arr).all(axis=1).any()
Post a Comment for "How To Check If A Numpy Array Is A Subarray Of Another Bigger Array"