python 二维矩阵中的索引

python index in 2d matrix

给定以下代码:

import numpy as np
mat = np.arange(1,26).reshape(5,5)

我的理解是以下几行是相同的:

mat[:3][1:2]
mat[:3,1:2]

但他们不是。为什么?

如果您在切片语法中仅指定一维,则只会切片一维。在 NumPy 中,索引中的维度通常由 ",".

分隔

对于二维数组,您可以将 "row" 替换为 "dimension 1",将 "column" 替换为 "dimension 2"。在您的示例中,mat[:3] 对前 3 行进行切片。随后的索引器 [1:2],对这 3 行中的第一行进行切片。

对于您的第二个示例,[:3, 1:2] 同时对行和列进行切片。

您可能会发现查看结果的形状很有帮助:

mat[:3].shape       # (3, 5)
mat[:3][1:2].shape  # (1, 5)
mat[:3,1:2].shape   # (3, 1)

你的矩阵:

array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])

第一个mat[:3][1:2]先拿mat[:3]再申请[1:2]:

mat[:3]
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15]])
# mat[:3][1:2] => array([[ 6,  7,  8,  9, 10]])

而第二个 (mat[:3,1:2]) 指出:

行最多 3

array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15]])

12

 array([[ 2],
       [ 7],
       [12]])

结论,主要区别是第一个在 [:3]

之后应用 [1:2]

原因如下:

> mat

# output:
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])

> mat[:3] # you are selecting the first 3 rows

#output:
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15]])

> mat[:3][1:2] # you are selecting the second row only

Output:
array([[ 6,  7,  8,  9, 10]])

> mat[:3,1:2] # you are selecting from the first 3 rows and the second column

Output:
array([[ 2],
       [ 7],
       [12]])