代码之家  ›  专栏  ›  技术社区  ›  PiMathCLanguage

如何为一个数组中包含在另一个数组中的值获取所有索引?

  •  2
  • PiMathCLanguage  · 技术社区  · 7 年前

    假设我们有两个简单的1d numpy数组:

    a = np.array([1, 1, 2, 5, 7, 8, 2, 4, 5, 6]) 
    b = np.array([1, 5, 7])
    

    现在我想得到所有可能的索引,其中数组中的每个值 b 包含在数组中 a .

    我们可以这样做,例如:

    idx = np.where(np.any(a.reshape((-1, 1))==b, axis=1))[0]
    

    哪里 idx array([0, 1, 3, 4, 8]) (这正是我真正想要的)。

    现在我真的很好奇numpy或任何其他库(我相信已经存在一个库)中是否已经有类似的函数来解决这个问题。否则我现在就坚持工作方法。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Divakar    7 年前

    具有 np.isin / np.in1d -

    np.flatnonzero(np.isin(a,b))
    # or np.flatnonzero(np.in1d(a,b))
    

    可能更适合 np.searchsorted b -

    sidx = np.searchsorted(b,a)
    sidx[sidx==len(b)] = len(b)-1
    out = np.flatnonzero(b[sidx]==a)
    

    如果 未排序,请对其排序,然后使用它代替 B