元组索引 numpy 数组的奇怪行为
Strange behavior of tuple indexing a numpy array
我注意到在使用元组列表(使用 python 2.7.8 和 numpy 1.9.1)索引平面 numpy 数组时出现一些令人困惑的行为。我的猜测是这与数组维度的最大数量(我认为是 32)有关,但我一直无法找到文档。
>>> 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...
元组列表是否 "flattened" 如果它是 32 个元素或更大?这在某处记录了吗?
区别似乎是第一个示例触发花式索引(它只是从同一维度中选择列表中的索引),而 tuple_index[:31]
被视为索引元组(这意味着从多个轴中选择).
如您所述,NumPy 数组的最大维数(通常)为 32:
>>> np.MAXDIMS
32
根据 mapping.c 文件中的以下注释(其中包含解释用户传递的索引的代码),任何短于 32 的元组序列都被展平为索引元组:
/*
* 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 站点的官方文档中找到这方面的参考资料。)
这使得 a[tuple_index[:3]]
等同于 a[(0,), (1,), (2,)]
,因此出现 "too many indices" 错误(因为 a
只有一个维度,但我们暗示有三个维度)。
另一方面,a[tuple_index]
与 a[[(0,), (1,), (2,), ..., (99,)]]
相同,生成二维数组。
我注意到在使用元组列表(使用 python 2.7.8 和 numpy 1.9.1)索引平面 numpy 数组时出现一些令人困惑的行为。我的猜测是这与数组维度的最大数量(我认为是 32)有关,但我一直无法找到文档。
>>> 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...
元组列表是否 "flattened" 如果它是 32 个元素或更大?这在某处记录了吗?
区别似乎是第一个示例触发花式索引(它只是从同一维度中选择列表中的索引),而 tuple_index[:31]
被视为索引元组(这意味着从多个轴中选择).
如您所述,NumPy 数组的最大维数(通常)为 32:
>>> np.MAXDIMS
32
根据 mapping.c 文件中的以下注释(其中包含解释用户传递的索引的代码),任何短于 32 的元组序列都被展平为索引元组:
/*
* 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 站点的官方文档中找到这方面的参考资料。)
这使得 a[tuple_index[:3]]
等同于 a[(0,), (1,), (2,)]
,因此出现 "too many indices" 错误(因为 a
只有一个维度,但我们暗示有三个维度)。
另一方面,a[tuple_index]
与 a[[(0,), (1,), (2,), ..., (99,)]]
相同,生成二维数组。