[英]How to find the index of a value in 2d array in Python?
我需要弄清楚如何在 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)]
一个索引。
您可以使用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
可以是一种更有效的生成对的方法。
您提供的列表理解的问题在于它只深入一层,您需要一个嵌套的列表理解:
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 建议的内置函数。
使用 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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.