问题
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])
>>> arr2 = np.array([0, 0, 1, 1, 1, 0])
>>> test_array = np.array([1, 1, 1])
>>> test_array in arr1
... False
>>> test_array in arr2
... True
Is there any way to solve do something like this? Thanks.
回答1:
The most intuitive way seems to be an iterative process like so:
def isSubset(arr1, arr2):
m = len(arr1)
n = len(arr2)
for i in range(0, n):
for j in range(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:
return False
"""
If we reach here then all
elements of arr2 are present
in arr1
"""
return True
回答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:
def array_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()
来源:https://stackoverflow.com/questions/56840763/how-to-check-if-a-numpy-array-is-a-subarray-of-another-bigger-array