python - 为什么 numpy 混合基本/高级索引取决于切片邻接?

标签 python numpy multidimensional-array numpy-ndarray

我知道之前有人问过类似的问题(e.g.),但据我所知,没有人回答我的具体问题...

我的问题是关于描述的 numpy 混合高级/基本索引 here :

... Two cases of index combination need to be distinguished:

  • The advanced indexes are separated by a slice, ellipsis or newaxis. For example x[arr1,:,arr2].
  • The advanced indexes are all next to each other. For example x[...,arr1,arr2,:] but not x[arr1,:,1] since 1 is an advanced index in this regard.

In the first case, the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that. In the second case, the dimensions from the advanced indexing operations are inserted into the result array at the same spot as they were in the initial array (the latter logic is what makes simple advanced indexing behave just like slicing).

为什么有必要进行这种区分?

我期望在所有情况下都使用针对案例 2 描述的行为。为什么索引是否彼此相邻很重要?

我知道在某些情况下您可能想要案例 1 的行为;例如,索引结果沿新维度的“矢量化”。但是这种行为可以而且应该由用户定义。也就是说,如果情况 2 的行为是默认的,则情况 1 的行为可能仅使用: x[arr1,:,arr2].reshape((len(arr1),x.shape[1]))

我知道您可以使用 np.ix_() 实现案例 2 中描述的行为,但在我看来,默认索引行为中的这种不一致是出乎意料且不合理的。有人可以证明吗?

谢谢,

最佳答案

情况 2 的行为对于情况 1 没有明确定义。您可能在以下句子中遗漏了一个微妙之处:

In the second case, the dimensions from the advanced indexing operations are inserted into the result array at the same spot as they were in the initial array

您可能想象输入和输出维度之间存在一对一的对应关系,这可能是因为您想象的是 Matlab 风格的索引。 NumPy 不是那样工作的。如果您有四个具有以下形状的数组:

a.shape == (2, 3, 4, 5, 6)
b.shape == (20, 30)
c.shape == (20, 30)
d.shape == (20, 30)

那么a[b, :, c, :, d]四个维度,长度分别为3、5、20、30。没有明确的地方将 20 和 30 放在前面。NumPy 默认将它们放在前面。

另一方面,对于 a[:, b, c, d, :],20 和 30 可以到达 3、4 和 5 所在的位置,因为 3、4 , 并且 5 个彼此相邻。新尺寸的整 block 位于原始尺寸的整 block 所在的位置,只有当原始尺寸在原始形状的单个 block 中时才有效。

关于python - 为什么 numpy 混合基本/高级索引取决于切片邻接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53841497/

相关文章:

python - NCO 下载 Python

python - 安装一堆软件包的任何有效方法

java - 需要帮助迭代在较大的二维数组中找到的较小的二维 "subarrays"

c++ - 访问 2D valarrays 的列切片

python - Python 3 和 SQLite3 的 `table "django_migrations "already exists` 错误

python - 使用 numpy.clip 将正值和负值转换为位串

python - 计算 python collections.Counter 中值的平均值

python - 在 scikit dict vectorizer 中按特征名称提取特征

android - 如何在ListView中显示二维数组?

python - 解析字段内带逗号的 CSV 文件