简体   繁体   English

如何在Python中的二维数组中找到值的索引?

[英]How to find the index of a value in 2d array in Python?

I need to figure out how I can find all the index of a value in a 2d numpy array.我需要弄清楚如何在 2d numpy 数组中找到一个值的所有索引。

For example, I have the following 2d array:例如,我有以下二维数组:

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

I need to find the index of all the 1's and 0's.我需要找到所有 1 和 0 的索引。

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]

Basically, it gives me only one of the index in each row [(0, 0), (1, 2)] .基本上,它只给我每行[(0, 0), (1, 2)]一个索引。

You can use np.where to return a tuple of arrays of x and y indices where a given condition holds in an array.您可以使用np.where返回 x 和 y 索引数组的元组,其中给定条件在数组中成立。

If a is the name of your array:如果a是数组的名称:

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

If you want a list of (x, y) pairs, you could zip the two arrays:如果你想要一个 (x, y) 对的列表,你可以zip这两个数组:

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

Or, even better, @jme points out that np.asarray(x).T can be a more efficient way to generate the pairs.或者,更好的是,@jme 指出np.asarray(x).T可以是一种更有效的生成对的方法。

The problem with the list comprehension you provided is that it only goes one level deep, you need a nested list comprehension:您提供的列表理解的问题在于它只深入一层,您需要一个嵌套的列表理解:

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)]

That being said, if you are working with a numpy array, it's better to use the built in functions as suggested by ajcr.话虽如此,如果您使用的是 numpy 数组,最好使用 ajcr 建议的内置函数。

Using numpy, argwhere may be the best solution:使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM