【问题标题】:How to find the indices of an ndarray in another ndarray [duplicate]如何在另一个ndarray中找到一个ndarray的索引[重复]
【发布时间】:2021-03-14 16:28:36
【问题描述】:

我有 a = np.arange(21).reshape(7,3) 和 b = np.array([[3,4,5], [9,10,11]]) 的数组

a = [[ 0  1  2]
     [ 3  4  5]
     [ 6  7  8]
     [ 9 10 11]
     [12 13 14]
     [15 16 17]
     [18 19 20]]

b = [[3  4  5]
     [9 10 11]]

我想在 a 中找到 b 的行号。因此,我希望将 1 和 3 作为我的 输出。我知道要查找索引,我可以使用np.where() 或np.argwhere()。但是,我不知道我们是否可以使用它们来解决这个问题,或者我必须使用其他功能。我试过c = np.argwhere(a == b),但它给出了错误。

【问题讨论】:

    标签: python python-3.x numpy indexing


    【解决方案1】:

    您可以按如下方式使用np.argwhere:

    import numpy as np
    
    a = np.array([[0, 1, 2],
                  [3, 4, 5],
                  [6, 7, 8],
                  [9, 10, 11],
                  [12, 13, 14],
                  [15, 16, 17],
                  [18, 19, 20]])
    
    b = np.array([[3, 4, 5],
                  [9, 10, 11]])
    
    res = np.argwhere(
        (a == b[:, None])  # compare all rows of a vs b
        .all(axis=2)  # find the ones where all the elements matches
    )[:, 1]  # use argwhere to find indices, but only use the column indices
    
    print(res)
    

    输出

    [1 3]
    

    更新 为了找到丢失的,请执行以下操作,我将步骤拆分以使其更易于理解:

    matches = (a == b[:, None]).all(axis=2)
    print(matches)
    
    res = np.argwhere(~matches.any(axis=1))[:, 0]
    print(res)
    

    输出

    [[False  True False False False False False]
     [False False False False False False False]]
    [1]
    

    输出的第一部分显示了与b 中的行相对应的两行,因为可以看出b 的第一行与a 的第二行匹配。第二行, 没有匹配项。

    输出的第二部分显示了应用 argwhere 来选择在b (~matches.any(axis=1)) 中没有a 行匹配的索引的结果。

    【讨论】:

    • 那是完美的。有效。只是我很想知道我们是否可以找到在 a 中找不到的 b 的哪些行?想象一下我有 b = np.array([[3,4,5], [21,22,23]])。我可以得到 1 的输出,它对应于不在 a 中的 b 的第二行吗?
    • @Peyman 更新了答案。
    • 是的,这正是我想要的。我真的很感激。
    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 2021-10-15
    • 2018-02-14
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多