【问题标题】:is there a method for finding the indexes of a 2d-array based on a given array有没有一种基于给定数组查找二维数组索引的方法
【发布时间】:2021-11-13 14:31:58
【问题描述】:

假设我们有两个这样的数组:

A=np.array([[1, 4, 3, 0, 5],[6, 0, 7, 12, 11],[20, 15, 34, 45, 56]])
B=np.array([[4, 5, 6, 7]])

我打算编写一个代码,在其中我可以根据 数组 B 例如,我希望最终结果是这样的:

C=[[0 1]
   [0 4]
   [1 0]
   [1 2]]

谁能给我一个解决方案或提示?

【问题讨论】:

  • 使用 C[row,col] 访问元素。
  • @SwapnalShahil 我认为 OP 正在寻找如何生成 C,而不是索引它。
  • 是的,很抱歉,感谢您的清理!

标签: python arrays numpy indexing


【解决方案1】:

你的意思是?

In [375]: np.isin(A,B[0])
Out[375]: 
array([[False,  True, False, False,  True],
       [ True, False,  True, False, False],
       [False, False, False, False, False]])
In [376]: np.argwhere(np.isin(A,B[0]))
Out[376]: 
array([[0, 1],
       [0, 4],
       [1, 0],
       [1, 2]])

B (1,4) 的形状,其中初始 1 不是必需的。这就是我使用B[0] 的原因,尽管isin,通过in1d 无论如何都无法解决。

where 是结果通常更有用

In [381]: np.where(np.isin(A,B))
Out[381]: (array([0, 0, 1, 1]), array([1, 4, 0, 2]))

虽然有点难理解。

另一种获取isin数组的方法:

In [383]: (A==B[0,:,None,None]).any(axis=0)
Out[383]: 
array([[False,  True, False, False,  True],
       [ True, False,  True, False, False],
       [False, False, False, False, False]])

【讨论】:

    【解决方案2】:

    您可以使用np.where()尝试这种方式。

    index = []
    for num in B:
        for nums in num:
            x,y = np.where(A == nums)
            index.append([x,y])
        
    print(index)
    
    >>array([[0,1],
            [0,4],
            [1,0],
            [1,2]])
    
    

    【讨论】:

      【解决方案3】:

      使用zipnp.where

      >>> list(zip(*np.where(np.in1d(A, B).reshape(A.shape))))
      [(0, 1), (0, 4), (1, 0), (1, 2)]
      

      或者:

      >>> np.vstack(np.where(np.isin(A,B))).transpose()
      array([[0, 1],
             [0, 4],
             [1, 0],
             [1, 2]], dtype=int64)
      

      【讨论】:

      • list(zip(* 是一个基于transpose 的列表。 np.argwherenp.transpose(np.where(...))
      猜你喜欢
      • 1970-01-01
      • 2019-07-24
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多