使用python范围对象索引到numpy数组

问题描述 投票:2回答:2

我之前看过一两次,但我似乎无法找到任何官方文档:使用python range对象作为numpy中的索引。

import numpy as np
a = np.arange(9).reshape(3,3)
a[range(3), range(2,-1,-1)]
# array([2, 4, 6])

让我们触发一个索引错误,只是为了确认范围不在合法索引方法的官方范围内(双关语):

a['x']

# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

现在,numpy与其文档之间的轻微差异并非完全闻所未闻,并不一定表明某个特征不是预期的(参见例如here)。

那么,有人知道为什么这个有用吗?如果它是一个预期的功能,那么什么是确切的语义/它有什么用呢?有没有ND概括?

python numpy array-indexing
2个回答
1
投票

不是一个正确的答案,但评论太久了。

事实上,它似乎适用于任何可索引对象:

import numpy as np

class MyIndex:
    def __init__(self, n):
        self.n = n
    def __getitem__(self, i):
        if i < 0 or i >= self.n:
            raise IndexError
        return i
    def __len__(self):
        return self.n

a = np.array([1, 2, 3])
print(a[MyIndex(2)])
# [1 2]

我认为NumPy代码中的相关行在core/src/multiarray/mapping.c的评论之下:

/*
 * Some other type of short sequence - assume we should unpack it like a
 * tuple, and then decide whether that was actually necessary.
 */

但我不完全确定。出于某种原因,如果你删除if i < 0 or i >= self.n: raise IndexError,即使有一个__len__,这也会挂起,所以在某些时候它似乎是在给定的对象中迭代,直到IndexError被提升。


1
投票

只是为了把它包起来(感谢评论中的@WarrenWeckesser):实际记录了这种行为。人们只需要意识到range对象是python序列in the strict sense

所以这只是花哨索引的一个例子。但要注意,它很慢:

>>> a = np.arange(100000)
>>> timeit(lambda: a[range(100000)], number=1000)
12.969507368048653
>>> timeit(lambda: a[list(range(100000))], number=1000)
7.990526253008284
>>> timeit(lambda: a[np.arange(100000)], number=1000)
0.22483703796751797
© www.soinside.com 2019 - 2024. All rights reserved.