Python 将 2D 数组附加到 3D 数组,扩展第三维
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34357617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append 2D array to 3D array, extending third dimension
提问by trminh89
I have an array A
that has shape (480, 640, 3)
, and an array B
with shape (480, 640)
.
我有一个A
具有 shape(480, 640, 3)
的数组和一个B
具有 shape的数组(480, 640)
。
How can I append these two as one array with shape (480, 640, 4)
?
如何将这两个附加为一个具有 shape 的数组(480, 640, 4)
?
I tried np.append(A,B)
but it doesn't keep the dimension, while the axis
option causes the ValueError: all the input arrays must have same number of dimensions
.
我试过了,np.append(A,B)
但它没有保留尺寸,而该axis
选项会导致ValueError: all the input arrays must have same number of dimensions
.
采纳答案by Alex Riley
Use dstack
:
使用dstack
:
>>> np.dstack((A, B)).shape
(480, 640, 4)
This handles the cases where the arrays have different numbers of dimensions and stacks the arrays along the third axis.
这处理数组具有不同维数并沿第三轴堆叠数组的情况。
Otherwise, to use append
or concatenate
, you'll have to make B
three dimensional yourself and specify the axis you want to join them on:
否则,要使用append
or concatenate
,您必须B
自己制作三维并指定要加入它们的轴:
>>> np.append(A, np.atleast_3d(B), axis=2).shape
(480, 640, 4)