Domagoj
Domagoj

Reputation: 1705

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. I am quite new in Numpy multidimensional arrays and basically I am missing something important here.

In this example I am trying to make 10x10x20 3D array using base 2D array(10x10) by copying it 20 times.

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:

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?

Cheers.

Edit Well I was doing things wrongly probably because of my R background.

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?

Upvotes: 0

Views: 464

Answers (2)

Barmaley
Barmaley

Reputation: 1232

Came across similar problem...

I needed to modify 2D array into 3D array like so: (y, x) -> (y, x, 3). Here is couple solutions for this problem.

Solution 1

Using python tool set

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

Solution 2

Using numpy tool set

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! This works but I suspect there is a better way performance-wise.

Upvotes: 1

plonser
plonser

Reputation: 3363

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

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

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

Upvotes: 1

Related Questions