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

时间:2023-01-31 21:30:05

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:

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

([[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)]中的一个索引。

2 个解决方案

#1


18  

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(*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可以是生成对的更有效方式。

#2


6  

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建议的内置函数。

#1


18  

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(*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可以是生成对的更有效方式。

#2


6  

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建议的内置函数。