如何在Python中找到2d数组中的值的索引?

Pet*_*ete 12 python arrays numpy multidimensional-array

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

例如,我有以下2d数组:

([[1 1 0 0],
  [0 0 1 1],
  [0 0 0 0]])
Run Code Online (Sandbox Code Playgroud)

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

1: [(0, 0), (0, 1), (1, 2), (1, 3)]
0: [(0, 2), (0, 3), (1, 0), (1, 1), (the entire all row)]
Run Code Online (Sandbox Code Playgroud)

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

t = [(index, row.index(1)) for index, row in enumerate(x) if 1 in row]
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*ley 23

您可以使用np.where返回给定条件在数组中保存的x和y索引数组的元组.

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

>>> np.where(a == 1)
(array([0, 0, 1, 1]), array([0, 1, 2, 3]))
Run Code Online (Sandbox Code Playgroud)

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

>>> zip(*np.where(a == 1))
[(0, 0), (0, 1), (1, 2), (1, 3)]
Run Code Online (Sandbox Code Playgroud)

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

  • 请注意:对于大的 `x`,`zip(*x)` 可能会很慢,其中 `x = np.where(a == 1)`。如果二维数组没问题,`np.asarray(x).T` 会快一些,如果你*真的*想要一个列表,`np.asarray(x).T.tolist() ` 稍微快一点。 (4认同)

Gui*_*ton 11

使用 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]]
Run Code Online (Sandbox Code Playgroud)


Mik*_*ike 9

你提供的列表理解的问题是它只有一个深度,你需要一个嵌套的列表理解:

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)]
Run Code Online (Sandbox Code Playgroud)

话虽这么说,如果你正在使用numpy数组,最好使用ajcr建议的内置函数.