Skip to main content
 首页 » 编程设计

python之为什么 Numpy 中的数组索引会产生这个结果

2024年12月31日9myhome

根据numpy documentation ,将数组索引指定为 array_name[x, y] 和 array_name[x][y] 是等效的,并且应该产生相同的结果。但是,下面的代码片段:

import numpy as np 
 
a = np.empty((7, 8, 9), dtype = object) 
# First indexing notation 
print(a[:, 0, 0].shape, a[0, :, 0].shape, a[0, 0, :].shape) 
# Second indexing notation 
print(a[:][0][0].shape, a[0][:][0].shape, a[0][0][:].shape) 

产生输出:

(7,) (8,) (9,)     
(9,) (9,) (9,) 

分别,这显然是不等价的。给了什么?

请您参考如下方法:

您误解了 numpy 如何解释索引/切片。对于类似 a[x, y, z] 的东西,numpy 使用 x 沿着第一个维度进行选择,使用 y 沿着第二个维度进行选择,并且z 沿着三维。

但是,对于 a[x][y][z],numpy 在 a 的第一个维度上使用 x,它沿 a[x] 的第一个维度使用 y,沿 a[x][y] 的第一个维度使用 z ]。

如果将使用 : 与使用一些数字进行比较,这可能会造成混淆。为什么会这样?一种是切片(:),另一种是索引(no :)。因为沿维度切片(使用 :)实际上不会减少数组的维度,而索引会。

可以有很多示例来说明这一点,但我认为您最好在 ipython 中使用数组进行游戏,看看不同的索引和切片如何影响输出。但是,我将提供一两个具体示例来回答您的问题

import numpy as np 
 
a = np.arange(2*3*4).reshape((2,3,4)) 
 
a 
array([[[ 0,  1,  2,  3], 
        [ 4,  5,  6,  7], 
        [ 8,  9, 10, 11]], 
 
       [[12, 13, 14, 15], 
        [16, 17, 18, 19], 
        [20, 21, 22, 23]]]) 
 
# First indexing notation 
print(a[:, 0, 0].shape, a[0, :, 0].shape, a[0, 0, :].shape) 
# Prints (2,) (3,), (4,) 

分解这个,我们把每一个:

  • a[:, 0, 0] 获取所有第一个维度,以及第二个和第三个维度的第 0 个元素。
  • a[0, :, 0] 取第一个维度的第 0 个元素,第二个维度的所有元素,以及 0 >三维的第一个元素。
  • a[0, 0, :] 为第一个和第二个维度获取第 0 个元素,为第三个维度获取所有元素。

# Second indexing notation 
print(a[:][0][0].shape, a[0][:][0].shape, a[0][0][:].shape) 
# Prints (4,) (4,) (4,) 

在这种情况下:

  • a[:] 与a 基本相同(返回矩阵的新view -- google "numpy view"for更多信息)。由于 a[:] 与 a 相同,a[:][0] 选择 0元素 沿 a
  • 的第一个维度
  • 等...

OP 说:

According the the numpy documentation, specifying array indices as array_name[x, y] and array_name[x][y] are equivalent

这是真的!要认识到的主要事情是(尽管相关)索引和切片不是一回事(正如我在上面指出的那样)。