NumPy 数组中元素的索引 [英] Index of element in NumPy array
问题描述
在 Python 中,我们可以使用 .index()
来获取数组中某个值的索引.
但是对于 NumPy 数组,当我尝试这样做时:
decoding.index(i)
我明白了:
<块引用>AttributeError: 'numpy.ndarray' 对象没有属性 'index'
如何在 NumPy 数组上执行此操作?
使用 np.where
获取给定条件为 True
的索引.
示例:
对于名为 a
的二维 np.ndarray
:
i, j = np.where(a == value) # 比较整数数组时i, j = np.where(np.isclose(a, value)) # 比较浮点数组时
对于一维数组:
i, = np.where(a == value) # 整数i, = np.where(np.isclose(a, value)) # 浮点数
请注意,这也适用于 >=
、<=
、!=
等条件...>
您还可以使用 index()
方法创建 np.ndarray
的子类:
class myarray(np.ndarray):def __new__(cls, *args, **kwargs):返回 np.array(*args, **kwargs).view(myarray)定义索引(自我,价值):返回 np.where(self == value)
测试:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])a.index(4)#(数组([ 3, 4, 5, 8, 9, 10]),)
In Python we can get the index of a value in an array by using .index()
.
But with a NumPy array, when I try to do:
decoding.index(i)
I get:
AttributeError: 'numpy.ndarray' object has no attribute 'index'
How could I do this on a NumPy array?
Use np.where
to get the indices where a given condition is True
.
Examples:
For a 2D np.ndarray
called a
:
i, j = np.where(a == value) # when comparing arrays of integers
i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays
For a 1D array:
i, = np.where(a == value) # integers
i, = np.where(np.isclose(a, value)) # floating-point
Note that this also works for conditions like >=
, <=
, !=
and so forth...
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)
Testing:
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屋!