如何在Python中的2d数组中找到值的索引? [英] How to find the index of a value in 2d array in Python?

查看:307
本文介绍了如何在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.

这篇关于如何在Python中的2d数组中找到值的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆