gpt4 book ai didi

python - NumPy 数组中元素的索引

转载 作者:IT老高 更新时间:2023-10-28 20:39:02 26 4
gpt4 key购买 nike

在 Python 中,我们可以使用 .index() 获取数组中某个值的索引。

但是对于 NumPy 数组,当我尝试这样做时:

decoding.index(i)

我明白了:

AttributeError: 'numpy.ndarray' object has no attribute 'index'

如何在 NumPy 数组上执行此操作?

最佳答案

使用 np.where获取给定条件为 True 的索引.

例子:

对于 2D np.ndarray调用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

对于一维数组:

i, = np.where(a == value) # integers

i, = np.where(np.isclose(a, value)) # floating-point

请注意,这也适用于 >= 等条件。 , <= , !=等等……

您也可以创建 np.ndarray 的子类与 index()方法:

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

关于python - NumPy 数组中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18079029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com