为什么 3D numpy 数组按原样打印(它们是如何排序的)?

Psy*_*ath 6 python numpy multidimensional-array numpy-ndarray

我试图理解 3D 数组(或者一般的多维数组),但这有点让我大吃一惊。尤其是 3D numpy 数组的打印方式对我来说是违反直觉的。这个问题类似,但更多的是关于编程语言之间的差异,我仍然没有完全理解。让我尝试解释一下。

假设我想创建一个 3 行(长度)、5 列(宽度)和 2 深度的 3D 数组。所以是一个 3x5x2 矩阵。

我执行以下操作:

import numpy as np
a = np.zeros(30).reshape(3, 5, 2)
Run Code Online (Sandbox Code Playgroud)

对我来说,打印此内容的逻辑方法如下:

[[[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.]]]
Run Code Online (Sandbox Code Playgroud)

但是,当我打印这个数组时,它会像这样打印:

[[[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.]]]
Run Code Online (Sandbox Code Playgroud)

我不清楚为什么数组会以这种方式打印。也许只是我(也许我的空间推理在这里缺乏),或者 NumPy 数组像这样打印有什么具体原因吗?

Psy*_*ath 5

将评论综合为正确的答案:

首先,看一下np.zeros(10).reshape(5, 2)。这是 5 行 2 列,而不是 2 行 5 列。前面加3表示5行2列的3个平面。你错过的是你的新维度位于前面而不是末尾。在数学中,通常在末尾添加额外的维度(就像用 az 扩展 (x,y) 变为 (x,y,z)。但是,在计算机科学中,数组维度通常是这样完成的。它反映了数组的方式通常以行优先顺序存储在内存中。