【发布时间】:2019-02-22 23:50:56
【问题描述】:
我正试图围绕 3D 数组(或一般的多维数组)展开思考,但这让我有点不知所措。特别是打印 3D numpy 数组的方式对我来说是违反直觉的。这个问题是similar,但更多的是关于编程语言之间的差异,我仍然没有完全理解。让我试着解释一下。
假设我想创建一个 3 行(长度)、5 列(宽度)和 2 深度的 3D 数组。所以一个 3x5x2 矩阵。
我执行以下操作:
import numpy as np
a = np.zeros(30).reshape(3, 5, 2)
对我来说,打印它的合乎逻辑的方式是这样的:
[[[0. 0. 0. 0. 0.] #We can still see three rows from top to bottom
[0. 0. 0. 0. 0.]] #We can still see five columns from left to right
[[0. 0. 0. 0. 0.] #Depth values are shown underneath each other
[0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]]
但是,当我打印这个数组时,它会像这样打印:
[[[0. 0.] #We can still see three rows from top to bottom,
[0. 0.] #However columns now also appear from top to bottom instead of from left to right
[0. 0.] #Depth values are now shown from left to right
[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]
[0. 0.]]]
我不明白为什么会以这种方式打印数组。也许只有我一个人(也许我这里缺乏空间推理),或者 NumPy 数组这样打印是否有特定原因?
【问题讨论】:
-
3x5x2 表示您有 3 个形状为 5x2 的数组。这就是你所看到的。 3 这里是深度。第一个数组是 5 行 2 列 (5x2),第二个数组是 5 行 2 列 (5x2),第三个数组是 5 行 2 列 (5x2)。该数组是逐层打印的
-
reshape(3, 2, 5)会得到预期的结果 -
首先,看看
np.zeroes(10).reshape(5, 2)。那是 5 行 2 列,而不是 2 行 5 列。前面加3表示5行2列3个平面。 -
您缺少的是新维度位于前端,而不是末端。
-
@Barmar 我明白了......所以你说的是当我使用 np.reshape() 添加维度(比如从 2D 到 3D)时,我应该总是添加额外的维度 在前面?你知道为什么会这样吗?因为在数学中,通常在末尾添加额外的维度(就像用 z 扩展 (x,y) 变成 (x,y,z)
标签: python numpy multidimensional-array numpy-ndarray