1

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.

  • Take a look at 2D pattern search Q&A - https://stackoverflow.com/questions/32531377/. To solve your case, with a [windows method](https://stackoverflow.com/a/32531759/) one would be - `(view_as_windows(arr2,len(test_array))==test_array).all(1).any()`. – Divakar Jul 01 '19 at 18:50

2 Answers2

0

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
0

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()
Tarifazo
  • 4,118
  • 1
  • 9
  • 22