python - 为什么使用 "colon and comma"进行切片与使用索引集合进行切片不同

标签 python numpy numpy-slicing

为什么使用“冒号和逗号”进行切片与使用索引集合进行切片不同?

下面是一个示例,我希望得到相同的结果,但事实并非如此:

import numpy as np

a = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])

print(a[[0,1],[0,1]])
# Output
# [[ 1  2  3]
#  [10 11 12]]

print(a[:,[0,1]])
# Output
# [[[ 1  2  3]
#   [ 4  5  6]]
#  [[ 7  8  9]
#   [10 11 12]]]

为什么它们不等价?

最佳答案

在第一种情况下,您使用 2 个相同长度的列表对数组 a 进行索引,这相当于使用 2 个相同形状的数组进行索引(请参阅 numpy docs on arrays as indices )。

因此,输出为 a[0,0] (与 a[0,0,:] 相同)和 a[1 ,1],索引数组的元素组合。预计会返回形状为 2,3 的数组。 2 因为它是索引数组的长度,3 因为它是未索引的轴。

在第二种情况下,结果是 a[:,0] (相当于 a[:,0,:])和 a[ :,1]。因此,这里期望的结果是一个数组,其第一维和第三维等于原始数组,第二维等于 2,即索引数组的长度(这里与第二轴的原始大小相同) .

为了清楚地表明这两个操作明显不同,我们可以尝试假设 : 与轴到第三轴的长度相同的范围之间是等价的,这将导致:

print(a[[0,1],[0,1],[0,1,2]])
IndexError                                Traceback (most recent call last)
<ipython-input-8-110de8f5f6d8> in <module>()
----> 1 print(a[[0,1],[0,1],[0,1,2]])

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (2,) (3,) 

这是因为索引数组不可能进行元素组合。与此相反,a[:,:,:] 将返回整个数组,a[[0,1],[0,1],[0,2]] 返回 [ 1 12] ,正如预期的那样,它是一个长度为 2 的一维数组,就像索引数组一样。

关于python - 为什么使用 "colon and comma"进行切片与使用索引集合进行切片不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50601068/

相关文章:

python - 在 python 3.5.1 中混合关键字和默认参数

python - 将字典传递给 Django 表单

python - django:TypeError: 'tuple' 对象不可调用

numpy - 在 OS X 10.7.4 上为 Python 3.2.3 安装 NumPy

python - 更新特定的 numpy 矩阵列

python - 如何纠正此 Damerau-Levenshtein 实现中的错误?

python - 这两行代码有什么区别?机器学习阵列

python / NumPy : How to extract interior of any dimension of numpy array?

python - 如何根据另一个二维数组中给出的索引对二维数组进行切片

python - 从 Numpy 数组中选择每列满足某些条件的所有行