在使用元组列表(使用 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...
如果元组列表是 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,)]
,因此“索引过多”错误(因为 a
只有一个维度,但我们暗示有三个维度)。
另一方面,a[tuple_index]
与 a[[(0,), (1,), (2,), ..., ( 99,)]]
生成二维数组。
关于python - 元组索引 numpy 数组的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30598517/