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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1727669/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:57:50  来源:igfitidea点击:

Contruct 3d array in numpy from existing 2d array

pythonnumpy

提问by vernomcrp

During preparing data for NumPy calculate. I am curious about way to construct:

在为 NumPy 计算准备数据期间。我对构建方式感到好奇:

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!

但它看起来不起作用!

采纳答案by Eric O Lebigot

hstack and vstack do no change the number of dimensions of the arrays: they merely put them "side by side". Thus, combining 2-dimensional arrays creates a new 2-dimensional array (not a 3D one!).

hstack 和 vstack 不会改变数组的维数:它们只是将它们“并排”放置。因此,组合二维数组会创建一个新的二维数组(不是 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 数组并获得d3您想要的新 3D 数组 ( )。

回答by Daniel G

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)

回答by Shu Zhang

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

arr1, arr2 are 2d array shape (256,256), arr3: shape(256,256,2)

arr1, arr2 是二维数组shape (256,256), arr3:shape(256,256,2)