简体   繁体   English

从现有的2d数组中构造numpy的3d数组

[英]Contruct 3d array in numpy from existing 2d array

During preparing data for NumPy calculate. 在为NumPy计算准备数据期间。 I am curious about way to construct: 我很好奇构建方式:

myarray.shape => (2,18,18)

from: 从:

d1.shape => (18,18)
d2.shape => (18,18)

I try to use NumPy command: 我尝试使用NumPy命令:

hstack([[d1],[d2]])

but it looks not work! 但它看起来不起作用!

Just doing d3 = array([d1,d2]) seems to work for me: 刚做d3 = array([d1,d2])似乎对我有用:

>>> from numpy import array
>>> # ... create d1 and d2 ...
>>> d1.shape
(18,18)
>>> d2.shape
(18,18)
>>> d3 = array([d1, d2])
>>> d3.shape
(2, 18, 18)

hstack and vstack do no change the number of dimensions of the arrays: they merely put them "side by side". hstack和vstack不会改变数组的维数:它们只是将它们“并排”。 Thus, combining 2-dimensional arrays creates a new 2-dimensional array (not a 3D one!). 因此,组合二维阵列会创建一个新的二维阵列(而不是一个3D阵列!)。

You can do what Daniel suggested (directly use numpy.array([d1, d2]) ). 你可以做Daniel建议的(直接使用numpy.array([d1, d2]) )。

You can alternatively convert your arrays to 3D arrays before stacking them, by adding a new dimension to each array: 您也可以在堆叠数组之前将数组转换为3D数组,方法是为每个数组添加一个新维度:

d3 = numpy.vstack([ d1[newaxis,...], d2[newaxis,...] ])  # shape = (2, 18, 18)

In fact, d1[newaxis,...].shape == (1, 18, 18) , and you can stack both 3D arrays directly and get the new 3D array ( d3 ) that you wanted. 事实上, d1[newaxis,...].shape == (1, 18, 18) ,你可以直接堆叠两个3D数组并获得你想要的新3D数组( d3 )。

arr3=np.dstack([arr1, arr2])

arr1,arr2是2d数组shape (256,256)shape (256,256)shape(256,256,2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM