是否有一个 NumPy 函数来返回数组中某物的第一个索引? [英] Is there a NumPy function to return the first index of something in an array?

查看:25
本文介绍了是否有一个 NumPy 函数来返回数组中某物的第一个索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一种方法可以让 Python 列表返回某事物的第一个索引:

<预><代码>>>>l = [1, 2, 3]>>>l.index(2)1

NumPy 数组有类似的东西吗?

解决方案

是的,给定一个数组,array 和一个值,item 来搜索,你可以使用 np.where如:

itemindex = numpy.where(array==item)

结果是一个元组,首先是所有行索引,然后是所有列索引.

例如,如果一个数组是二维的并且它在两个位置包含您的项目,则

array[itemindex[0][0]][itemindex[1][0]]

将等于您的项目,因此将是:

array[itemindex[0][1]][itemindex[1][1]]

I know there is a method for a Python list to return the first index of something:

>>> l = [1, 2, 3]
>>> l.index(2)
1

Is there something like that for NumPy arrays?

解决方案

Yes, given an array, array, and a value, item to search for, you can use np.where as:

itemindex = numpy.where(array==item)

The result is a tuple with first all the row indices, then all the column indices.

For example, if an array is two dimensions and it contained your item at two locations then

array[itemindex[0][0]][itemindex[1][0]]

would be equal to your item and so would be:

array[itemindex[0][1]][itemindex[1][1]]

这篇关于是否有一个 NumPy 函数来返回数组中某物的第一个索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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