问题描述
我索引元组(使用python 2.7.8和1.9.1 numpy的)列表的扁平numpy的阵列时,发现一些容易混淆的行为。我的猜测是,这是关系到阵列的尺寸(我相信这是32)的最大数目,但我一直没能找到的文档。
I noticed some confusing behavior when indexing a flat numpy array with a list of tuples (using python 2.7.8 and numpy 1.9.1). My guess is that this is related to the maximum number of array dimensions (which I believe is 32), but I haven't been able to find the documentation.
>>> a = np.arange(100)
>>> tuple_index = [(i,) for i in a]
>>> a[tuple_index] # This works (but maybe it shouldn't)
>>> a[tuple_index[:32]] # This works too
>>> a[tuple_index[:31]] # This breaks for 2 <= i < 32
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
>>> a[tuple_index[:1]] # This also works...
时的元组的列表是被夷为平地,如果它是32元以上?这是记录在案的地方?
Is the list of tuples is being "flattened" if it is 32 elements or larger? Is this documented somewhere?
推荐答案
的差异似乎是与第一实施例触发花式索引(其简单地从相同尺寸的列表中选择索引)而 tuple_index [31]
代替视为索引元组(从多轴意味着选择)
The difference appears to be that the first examples trigger fancy indexing (which simply selects indices in a list from the same dimension) whereas tuple_index[:31]
is instead treated as an indexing tuple (which implies selection from multiple axes).
如您所指出的,尺寸为numpy的阵列的最大数(通常)32:
As you noted, the maximum number of dimensions for a NumPy array is (usually) 32:
>>> np.MAXDIMS
32
根据在 mapping.c 文件(其中包含code国米preT用户通过指数),元组比32短展平到一个索引元组的任何序列:
According to the following comment in the mapping.c file (which contains the code to interpret the index passed by the user), any sequence of tuples shorter than 32 is flattened to an indexing tuple:
/*
* Sequences < NPY_MAXDIMS with any slice objects
* or newaxis, Ellipsis or other arrays or sequences
* embedded, are considered equivalent to an indexing
* tuple. (`a[[[1,2], [3,4]]] == a[[1,2], [3,4]]`)
*/
(我还没有找到在现场SciPy的官方文档在此引用。)
(I haven't yet found a reference for this in the official documentation on the SciPy site.)
这使得 A [tuple_index [3]
等同于 A [(0),(1),(2) ]
,因而有太多的指数的错误(因为 A
只有一个维度,但我们正在暗示有三个)。
This makes a[tuple_index[:3]]
equivalent to a[(0,), (1,), (2,)]
, hence the "too many indices" error (because a
has only one dimension but we're implying there are three).
在另一方面, A [tuple_index]
是一样的为 A [[(0),(1),( 2,),...,(99,)]]
所得的二维阵列中的
On the other hand, a[tuple_index]
is just the same as a[[(0,), (1,), (2,), ..., (99,)]]
resulting in the 2D array.
这篇关于元组的奇怪行为索引一个numpy的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!