check if numpy array is subset of another array

后端 未结 4 1908
广开言路
广开言路 2020-12-20 00:03

Similar questions have already been asked on SO, but they have more specific constraints and their answers don\'t apply to my question.

Generally speaking, what is t

4条回答
  •  死守一世寂寞
    2020-12-20 00:42

    You can do this easily via iterating over an array in list comprehension. A toy example is as follows:

    import numpy as np
    x = np.arange(30).reshape(10,3)
    searchKey = [4,5,8]
    x[[0,3,7],:] = searchKey
    x
    

    gives

     array([[ 4,  5,  8],
            [ 3,  4,  5],
            [ 6,  7,  8],
            [ 4,  5,  8],
            [12, 13, 14],
            [15, 16, 17],
            [18, 19, 20],
            [ 4,  5,  8],
            [24, 25, 26],
            [27, 28, 29]])
    

    Now iterate over the elements:

    ismember = [row==searchKey for row in x.tolist()]
    

    The result is

    [True, False, False, True, False, False, False, True, False, False]
    

    You can modify it for being a subset as in your question:

    searchKey = [2,4,10,5,8,9]  # Add more elements for testing
    setSearchKey = set(searchKey)
    ismember = [setSearchKey.issuperset(row) for row in x.tolist()]
    

    If you need the indices, then use

    np.where(ismember)[0]
    

    It gives

    array([0, 3, 7])
    

提交回复
热议问题