对于数组:
import numpy as np
arr2d = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> arr2d
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> arr2d[2].shape
(3,)
>>> arr2d[2:,:].shape
(1, 3)
当两个语句都返回第 3 行时,为什么我得到不同的形状?在这两种情况下,结果不应该是 (1,3) 因为我们返回的是包含 3 列的单行吗?
请您参考如下方法:
Why do I get different shapes when both statements return the 3rd row?
因为第一个操作是索引行,并且只选择一个元素,这在 single-element indexing 中提到过多维数组的段落 - 返回具有较低维度的数组(一维数组)。
在第二个示例中,您使用的是 slice如冒号所示。切片操作不会减少数组的维度。这也是合乎逻辑的,因为想象一下数组不会有 3 行而是 4 行。然后 arr2d[2:,:].shape 将是 (2,3)。 numpy 的开发人员使切片操作保持一致,因此他们(切片)永远不会减少数组的维数。
and shouldn't the result be (1,3) in both cases since we are returning a single row with 3 columns?
不是,只是因为前面的原因。
