How to check if a Numpy array is a subarray of another bigger array

老子叫甜甜 提交于 2019-12-24 07:34:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!