使用python range对象索引到numpy数组 [英] Using python range objects to index into numpy arrays
问题描述
我之前看过一两次,但是似乎找不到任何官方文档:使用python range
对象作为numpy中的索引.
I've seen it once or twice before, but I can't seem to find any official docs on it: Using python range
objects as indices in numpy.
import numpy as np
a = np.arange(9).reshape(3,3)
a[range(3), range(2,-1,-1)]
# array([2, 4, 6])
让我们触发一个索引错误只是为了确认范围不在合法索引方法的官方范围(双关语意图)之内:
Let's trigger an index error just to confirm that ranges are not in the official range (pun intended) of legal indexing methods:
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与它的文档之间的细微差别并不是完全闻所未闻的,并且不一定表明不打算使用某项功能(例如,请参见
Now, a slight divergence between numpy and its docs is not entirely unheard of and does not necessarily indicate that a feature is not intended (see for example here).
那么,有人知道这为什么起作用吗?并且,如果这是预期的功能,则确切的语义是什么?它的优点是什么?还有ND推广吗?
So, does anybody know why this works at all? And if it is an intended feature what are the exact semantics / what is it good for? And are there any ND generalizations?
推荐答案
仅需对此进行总结(感谢@WarrenWeckesser的评论):实际上已记录了此行为.只需意识到range
对象是python序列
Just to wrap this up (thanks to @WarrenWeckesser in the comments): This behavior is actually documented. One only has to realize that range
objects are python sequences in the strict sense.
因此,这只是花哨的索引的一种情况.但是请注意,它非常慢:
So this is just a case of fancy indexing. Be warned, though, that it is very slow:
>>> 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
这篇关于使用python range对象索引到numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!