[英]Append 2d array to 3d array
I have an array of shape (3, 250, 15)
.我有一个形状数组(3, 250, 15)
。
I want to append to it a 2d array of shape (250,15)
so that I have a final shape of (4,250,15)
.我想在其上附加一个形状为(250,15)
的二维数组,以便我的最终形状为(4,250,15)
。 I tried with dstack
and np.stack
but it does not work.我尝试使用dstack
和np.stack
但它不起作用。
Can someone give me a suggestion ?有人可以给我一个建议吗?
You need to add a dimension (in other words, an axis) to the 2-D array, for example:您需要向二维数组添加一个维度(换句话说,一个轴),例如:
import numpy as np
a = np.ones((3, 250, 15))
b = np.ones((250, 15))
c = np.vstack([a, b[None, :, :]])
Now c
has shape (4, 250, 15)
.现在c
具有形状(4, 250, 15)
。
If you're not into the None
axis trick, you could achieve something similar with np.newaxis
or np.reshape
.如果您不喜欢None
轴技巧,您可以使用np.newaxis
或np.reshape
实现类似的效果。
You can't append a 2D array to a 3D array directly, so you should first expand the axes of the smaller array to become 3D and then append normally.不能直接将 2D 数组附加到 3D 数组,因此应先将较小数组的轴扩展为 3D,然后正常附加。 np.expand_dims(b, axis=0)
will insert the missing first-axis to array b
. np.expand_dims(b, axis=0)
将丢失的第一轴插入数组b
。 Now append the two 3D arrays, np.append(a, b, axis=0)
.现在附加两个 3D 数组np.append(a, b, axis=0)
。
import numpy as np
a = np.ones((3, 250, 15))
b = np.ones(( 250, 15))
b = np.expand_dims(b, axis=0)
c = np.append(a, b, axis=0)
which works as expected.按预期工作。
print(c.shape)
(4, 250, 15)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.