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

问题描述:

我需要弄清楚如何在二维numpy数组中找到一个值的所有索引.

I need to figure out how I can find all the index of a value in a 2d numpy array.

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

For example, I have the following 2d array:

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

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

I need to find the index of all the 1's and 0's.

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

我尝试过此方法,但它并没有提供所有索引:

I tried this but it doesn't give me all the indexes:

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

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

Basically, it gives me only one of the index in each row [(0, 0), (1, 2)].

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

You can use np.where to return a tuple of arrays of x and y indices where a given condition holds in an array.

如果a是数组的名称:

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

如果要获得(x,y)对的列表,可以zip这两个数组:

If you want a list of (x, y) pairs, you could zip the two arrays:

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

或者更好的是,@ jme指出np.asarray(x).T是生成配对的一种更有效的方法.

Or, even better, @jme points out that np.asarray(x).T can be a more efficient way to generate the pairs.