【问题标题】:How to find the index of a value in 2d array in Python?如何在 Python 中找到二维数组中的值的索引?
【发布时间】:2015-01-26 07:55:48
【问题描述】:

我需要弄清楚如何在 2d numpy 数组中找到一个值的所有索引。

例如,我有以下二维数组:

([[1 1 0 0],
  [0 0 1 1],
  [0 0 0 0]])

我需要找到所有 1 和 0 的索引。

1: [(0, 0), (0, 1), (1, 2), (1, 3)]
0: [(0, 2), (0, 3), (1, 0), (1, 1), (the entire all row)]

我试过了,但它没有给我所有的索引:

t = [(index, row.index(1)) for index, row in enumerate(x) if 1 in row]

基本上,它只给了我每行中的一个索引[(0, 0), (1, 2)]

【问题讨论】:

  • 这实际上是一个numpy数组吗?
  • 是的,它的 。我实际上有一个大的二维数组,我是从提取图像中得到的。
  • 只有一和零吗?
  • 不在我的实际二维数组中,但在示例中是的。

标签: python arrays numpy multidimensional-array


【解决方案1】:

您可以使用 np.where 返回一个包含 x 和 y 索引数组的元组,其中给定条件在数组中成立。

如果a 是您的数组的名称:

>>> np.where(a == 1)
(array([0, 0, 1, 1]), array([0, 1, 2, 3]))

如果你想要一个 (x, y) 对的列表,你可以zip 两个数组:

>>> zip(*np.where(a == 1))
[(0, 0), (0, 1), (1, 2), (1, 3)]

或者,更好的是,@jme 指出np.asarray(x).T 可以是生成对的更有效方式。

【讨论】:

  • 请注意:zip(*x) 对于大型x 可能会很慢,其中x = np.where(a == 1)。如果二维数组没问题,np.asarray(x).T 会快很多,如果您真的想要列表列表,np.asarray(x).T.tolist() 会稍微快一些。
【解决方案2】:

您提供的列表理解的问题在于它只深入一层,您需要嵌套列表理解:

a = [[1,0,1],[0,0,1], [1,1,0]]

>>> [(ix,iy) for ix, row in enumerate(a) for iy, i in enumerate(row) if i == 0]
[(0, 1), (1, 0), (1, 1), (2, 2)]

话虽如此,如果您使用的是 numpy 数组,最好使用 ajcr 建议的内置函数。

【讨论】:

    【解决方案3】:

    使用 numpy,argwhere 可能是最好的解决方案:

    import numpy as np
    
    array = np.array([[1, 1, 0, 0],
                      [0, 0, 1, 1],
                      [0, 0, 0, 0]])
    
    solutions = np.argwhere(array == 1)
    print(solutions)
    
    >>>
    [[0 0]
     [0 1]
     [1 2]
     [1 3]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2019-07-24
      • 2021-03-18
      • 1970-01-01
      相关资源
      最近更新 更多