NumPy数组中的元素索引 [英] Index of element in NumPy array
本文介绍了NumPy数组中的元素索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,我们可以使用.index()获取数组中值的索引。我怎么能用NumPy数组呢?
In Python we can get the index of a value in an array by using .index(). How can I do it with a NumPy array?
当我尝试做的时候
decoding.index(i)
它说NumPy库不支持这个功能。有办法吗?
it says that the NumPy library doesn't support this function. Is there a way to do it?
推荐答案
使用 np.where
获取给定条件下的索引是 True
。
Use np.where
to get the indices where a given condition is True
.
示例:
对于2D np.ndarray
:
i, j = np.where(a == value)
对于1D数组:
i, = np.where(a == value)
适用于> =
,< =
,等条件! =
等等......
Which works for conditions like >=
, <=
, !=
and so forth...
您还可以创建 np.ndarray的子类
使用 index()
方法:
You can also create a subclass of np.ndarray
with an index()
method:
class myarray(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(myarray)
def index(self, value):
return np.where(self == value)
测试:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)
这篇关于NumPy数组中的元素索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文