numpy 将二维数组附加到三维数组

huangapple go评论55阅读模式
英文:

numpy appending a 2D array to a 3D array

问题

我会感激在将一个二维零数组附加到一个三维数组上方面的指导。这样可以向一个2x2矩阵添加多个层。

#所以,
n = np.zeros((1,3,3,), np.ubyte)
n[0][0][1] = n[0][1][0] = 1
#返回输出:
[[[0, 1, 0],
  [1, 0, 0],
  [0, 0, 0]]]

然后如何将另一个二维零元素数组添加到,以伪代码形式表示:

a = np.zeros((3,3,), np.ubyte)
n = np.append(n, a)
#返回输出:
 [[[0 1 0]
   [1 0 0]
   [0 0 0]]

  [[0 0 0]
   [0 0 0]
   [0 0 0]]]

以及对后两行进行如下操作,以添加任意数量的3x3二维矩阵的层。感谢您提前,卢卡斯。

英文:

i'd appreciate guidance on appending a 2D zeros array to a 3D array. so as to add multiple layers to a 2x2 matrix.

#so, 
n = np.zeros((1,3,3,), np.ubyte)
n[0][0][1] = n[0][1][0] = 1
#return prints:
[[[0, 1, 0],
  [1, 0, 0],
  [0, 0, 0]]]

then how do you add another 2D array of zero elements to, in pseudocode:

a = np.zeros((3,3,), np.ubyte)
n = np.append(n, a)
#return prints:
 [[[0 1 0]
   [1 0 0]
   [0 0 0]]

  [[0 0 0]
   [0 0 0]
   [0 0 0]]]

and so on with the latter two lines to add any number of layers of the 3x3 2D matrix.

thank you in advance, lucas

答案1

得分: 1

通常,数组需要具有相同的形状。要沿着现有轴连接,您可以使用 np.concatenate

np.concatenate([n, a[None,...]], axis=0)

注意,这会向 a 添加一个额外的维度,或者等效地,我们可以使用 np.stack 沿着新轴进行扩展:

np.stack([n[0], a], axis=0)

请注意,在上述情况下,我们删除了 n 的一个维度。

正如注释中所指出的,这是低效的,它将非常低效(总大小的二次时间增长),所以请记住这一点。

请注意,arr[0]arr[None, ...] 都是“廉价”的操作(常数时间),它们不会复制底层缓冲区,而是创建视图。

英文:

Generally, the arrays need to have the same shape. To join along an existing axis, you can use np.concatenate:

np.concatenate([n, a[None,...]], axis=0)

Note, this adds an extra dimension to a, or equivalently, we can extend along a new axis using np.stack:

np.stack([n[0], a], axis=0)

Note, in the above case, we removed a dimension from n.

As noted in the comments though, this is inefficient, this will scale very inefficiently (quadratic time on the total size), so keep that in mind.

Note, bot arr[0] and arr[None, ...] are "cheap" operations (constant time) and don't copy the underlying buffer, they create views.

huangapple
  • 本文由 发表于 2023年4月4日 04:45:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923637.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定