切片索引如何在 numpy 数组中工作

How does slice indexing work in numpy array

假设我们有一个数组

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

现在我有以下

row_r1 = a[1, :]
row_r2 = a[1:2, :]

print(row_r1.shape)
print(row_r2.shape)

我不明白为什么row_r1.shape是(4,)而row_r2.shape是(1,4)

它们的形状不应该都等于(4,)吗?

我喜欢这样想。第一种方式 row[1, :],声明像这样获取第 1 行的所有值:

返回: array([5, 6, 7, 8])

形状

(4,) numpy 数组中的四个值。

第二个 row[1:2, :] 表示去获取索引 1 和索引 2 之间的数据片段:

返回:

array([[5, 6, 7, 8]]) 注:双括号

形状

(1,4) np.array.

一行中的四个值

它们的形状不同,因为它们不是同一种东西。您可以通过打印它们来验证:

import numpy as np

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

row_r1 = a[1, :]
row_r2 = a[1:2, :]

print("{} is shape {}".format(row_r1, row_r1.shape))
print("{} is shape {}".format(row_r2, row_r2.shape))

产量:

[5 6 7 8] is shape (4,)
[[5 6 7 8]] is shape (1, 4)

这是因为索引将 return 一个元素,而切片将 return 一个数组。但是,您可以使用 numpy 数组可用的 .resize() 函数将它们操纵为同一事物。 代码:

import numpy as np

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

row_r1 = a[1, :]
row_r2 = a[1:2, :]

print("{} is shape {}".format(row_r1, row_r1.shape))
print("{} is shape {}".format(row_r2, row_r2.shape))
# Now resize row_r1 to be the same shape
row_r1.resize((1, 4))
print("{} is shape {}".format(row_r1, row_r1.shape))
print("{} is shape {}".format(row_r2, row_r2.shape))

产量

[5 6 7 8] is shape (4,)
[[5 6 7 8]] is shape (1, 4)
[[5 6 7 8]] is shape (1, 4)
[[5 6 7 8]] is shape (1, 4)

表明您实际上正在处理同一个形状的对象。希望这有助于清除它!