NumPy数组中元素的索引

2024-03-28 13:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我试着做的时候

decoding.index(i)

它说NumPy库不支持这个功能。有办法吗?


Tags: 功能numpyindex数组办法decoding
3条回答

我在实现NumPy数组索引的两种方法之间左右为难:

idx = list(classes).index(var)
idx = np.where(classes == var)

两者的字符数相同,但第一个方法返回的是int,而不是numpy.ndarray

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

示例:

对于名为a的二维np.ndarray

i, j = np.where(a == value) # when comparing arrays of integers

i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays

对于1D数组:

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

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

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

还可以使用index()方法创建np.ndarray的子类:

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数组转换为list并获取其索引。

例如:

tmp = [1,2,3,4,5] #python list
a = numpy.array(tmp) #numpy array
i = list(a).index(2) # i will return index of 2, which is 1

这正是你想要的。

相关问题 更多 >