【问题标题】:Strange behavior of tuple indexing a numpy array元组索引numpy数组的奇怪行为
【发布时间】:2015-08-16 09:20:45
【问题描述】:

在使用元组列表(使用 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 个或更大的元素,它会被“扁平化”吗?这是否记录在某处?

【问题讨论】:

  • 有趣的是,我收到一条不同的错误消息:IndexError: unsupported iterator index。使用 python 2.7 和 numpy 1.8.2
  • 抱歉,我应该指定版本(python 2.7.8;numpy 1.9.1)。我已经更新了问题。

标签: python arrays numpy indexing


【解决方案1】:

不同之处似乎在于第一个示例触发了精美的索引(它只是从同一维度选择列表中的索引),而 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,)]] 相同,生成二维数组。

【讨论】:

  • basics documentation 声称 索引数组必须是整数类型。 显然,实现无论如何都允许这样做。我仍然不明白为什么你从大于np.MAXDIMS的元组列表中得到一个二维数组。
  • 我同意这似乎并不明显(而且我不知道它是否有意)。当长于 MAXDIMS it looks like 时,元组列表 [(0,), (1,), (2,) ..., (99,)] 在内部被强制转换为 NumPy 数组(它将成为二维数组)。然后用它来索引原始的一维数组(返回一个二维数组)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 2019-04-13
  • 1970-01-01
  • 2018-07-10
  • 2017-05-05
  • 2019-08-30
相关资源
最近更新 更多