【问题标题】:Find indices of rows of numpy 2d array in another 2D array在另一个二维数组中查找 numpy 二维数组行的索引
【发布时间】:2021-03-03 22:33:19
【问题描述】:

我是 numpy 的新手。 我有 2 个二维数组。我想在 arr1 中找到 arr2 的索引。请给我建议。

    arr1 = [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9],
            [4, 5, 6],
            [1, 2, 3]]

    arr2 = [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]]
    
    desired_output = [0, 1, 2, 1, 0]

【问题讨论】:

    标签: numpy numpy-ndarray


    【解决方案1】:

    实现这一目标的一种方法。

    如果在arr2 中没有找到arr1 的任何行,则为简单起见,pos 中的该位置将具有值-1

    这大量使用了 numpy broadcastingindexing。随时要求进一步澄清。

    原始示例:

    import numpy as np
    arr1 = np.array([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9],
                     [4, 5, 6],
                     [1, 2, 3]])
    arr2 = np.array([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])
    
    inds = arr1 == arr2[:, None]
    row_sums = inds.sum(axis = 2)
    i, j = np.where(row_sums == 3) # Check which rows match in all 3 columns
    
    pos = np.ones(arr1.shape[0], dtype = 'int64') * -1
    pos[j] = i
    pos
    
    array([0, 1, 2, 1, 0])
    

    示例 2:

    import numpy as np
    arr1 = np.array([[1, 2, 4],
                     [4, 5, 6],
                     [7, 8, 9],
                     [4, 1, 6],
                     [1, 2, 3]])
    arr2 = np.array([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])
    
    inds = arr1 == arr2[:, None]
    row_sums = inds.sum(axis = 2)
    i, j = np.where(row_sums == 3)
    
    pos = np.ones(arr1.shape[0], dtype = 'int64') * -1
    pos[j] = i
    pos
    
    array([-1,  1,  2, -1,  0])
    

    如果您有更多列,只需将行 i, j = np.where(row_sums == 3) 更改为 i, j = np.where(row_sums == arr1.shape[1])

    【讨论】:

    • 非常感谢,这正是我需要的
    猜你喜欢
    • 2012-04-10
    • 2020-07-30
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多