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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27175400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:30:21  来源:igfitidea点击:

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

pythonarraysnumpymultidimensional-array

提问by Pete

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

采纳答案by Alex Riley

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

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

If ais 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 zipthe 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).Tcan be a more efficient way to generate the pairs.

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

回答by Mike

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

回答by Guillaume Lebreton

Using numpy, argwheremay 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]]