简体   繁体   English

从基本2D数组构造3D数组-Numpy

[英]Constructing 3D array from base 2D array - Numpy

I am trying to create 3D array in python using Numpy and by multiplying 2D array in to 3rd dimension. 我正在尝试使用Numpy在python中创建3D数组,并将2D数组乘以3维。 I am quite new in Numpy multidimensional arrays and basically I am missing something important here. 我在Numpy多维数组中是一个新手,基本上我在这里缺少重要的东西。

In this example I am trying to make 10x10x20 3D array using base 2D array(10x10) by copying it 20 times. 在此示例中,我尝试通过复制20次来使用基本2D数组(10x10)制作10x10x20 3D数组。

My starting 2D array: 我的起始二维数组:

a = zeros(10,10)
for i in range(0,9):
    a[i+1, i] = 1

What I tried to create 3D array: 我试图创建3D数组的内容:

b = zeros(20)
for i in range(0,19):
    b[i]=a

This approach is probably stupid. 这种方法可能很愚蠢。 So what is correct way to approach construction of 3D arrays from base 2D arrays? 那么从基础2D阵列构造3D阵列的正确方法是什么?

Cheers. 干杯。

Edit Well I was doing things wrongly probably because of my R background. 编辑好吧,由于我的R背景,我做错了事情。

Here is how I did it finally 我终于做到了

b = zeros(20*10*10)
b = b.reshape((20,10,10))
for i in b:
    for m in range(0, 9):
        i[m+1, m] = 1

Are there any other ways to do the same? 还有其他方法可以做到这一点吗?

There are many ways how to construct multidimensional arrays. 有很多方法可以构造多维数组。

If you want to construct a 3D array from given 2D arrays you can do something like 如果要从给定的2D数组构造3D数组,则可以执行以下操作

import numpy

# just some 2D arrays with shape (10,20)
a1 = numpy.ones((10,20))
a2 = 2* numpy.ones((10,20))
a3 = 3* numpy.ones((10,20))

# creating 3D array with shape (3,10,20)
b = numpy.array((a1,a2,a3))

Depending on the situation there are other ways which are faster. 根据情况,还有其他更快的方法。 However, as long as you use built-in constructors instead of loops you are on the fast side. 但是,只要您使用内置的构造函数而不是循环,您的立场就会很快。

For your concrete example in Edit I would use numpy.tri 对于您在Edit的具体示例,我将使用numpy.tri

c = numpy.zeros((20,10,10))
c[:] = numpy.tri(10,10,-1) - numpy.tri(10,10,-2)

Came across similar problem... 遇到类似的问题...

I needed to modify 2D array into 3D array like so: (y, x) -> (y, x, 3) . 我需要像这样将2D数组修改为3D数组: (y, x) -> (y, x, 3) Here is couple solutions for this problem. 这是此问题的几个解决方案。

Solution 1 解决方案1

Using python tool set 使用python工具集

array_3d = numpy.zeros(list(array_2d.shape) + [3], 'f')
for z in range(3):
    array_3d[:, :, z] = array_2d.copy()

Solution 2 解决方案2

Using numpy tool set 使用numpy工具集

array_3d = numpy.stack([array_2d.copy(), ]*3, axis=2)

That is what I came up with. 这就是我想出的。 If someone knows numpy to give a better solution I would love to see it! 如果有人知道numpy提供更好的解决方案,我很乐意看到它! This works but I suspect there is a better way performance-wise. 这可行,但是我怀疑有一种更好的性能方法。

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

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