如果数组x
的声明如下:
x = np.array([[1, 2], [3, 4]])
x = [1, 2]
The shape of x
is (2,)
, which indicates a one-dimensional array with 2 elements.
x = np.array([1, 2, 3])
为什么
x
的形状是(3,)
而不是(1,3)
?我误认为形状应该是(行,列)
的形式了吗?因为np.array([1,2,3])
是一维数组。(3,)
表示这是具有三个元素的单个维度。
(1,3)
表示这是一个二维数组。
如果你在数组上使用reshape()
方法,并给它参数(1,3)
,它将添加额外的方括号。
>>> np.array([1,2,3]).reshape(1,3)
array([[1, 2, 3]])
np.array
代表一个n维数组。这可能包括一个二维数组来表示矩阵,其中(行,列)
是适当的。它也可以包括一维、三维或其他数组,对于这些数组,(行,列)
的维度过多/过少。比较:
>>> # 1-dimensional
>>> np.array([1, 2, 3]).shape
(3,)
>>> np.array([1, 2, 3])[1]
2
>>> # 2-dimensional
>>> np.array([[1, 2, 3]]).shape
(1, 3)
>>> np.array([[1, 2, 3]])[0,1]
2
>>> np.array([[1], [2], [3]]).shape
(3, 1)
>>> np.array([[1], [2], [3]])[1, 0]
2
>>> # 3-dimensional
>>> np.array([[[1, 2, 3]]]).shape
(1, 1, 3)
>>> np.array([[[1, 2, 3]]])[0,0,1]
2
>>> np.array([[[1,2],[3,4]],[[5, 6], [7, 8]]]).shape
(2, 2, 2)
(3,)
, (1, 3)
, (3, 1)
, (1, 1, 3)
... 表示不同的逻辑布局,例如特定元素所在位置的不同。
[1,2,3]
是一维的,[[1,2],[3,4]]
是二维的。比较[[[1,2],[3,4]],[[5, 6], [7, 8]]]
。"(行, 列)" 描述的是矩阵,而不是 n 维数组。 - MisterMiyagishape
中数字的数量,而数字本身则表示每个对应括号集合中有多少元素。 - Tomerikoo