Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3D tiling of a numpy array

Provided a 1D array as a:

a=np.arange(8)

I would like it to be reproduced in a 3D scheme in order to have such shape (n1, len(a), n3). Is there any working way to obtain this via np.tile? It seems trivial, but trying:

np.shape(  np.tile(a, (n1,1,n3))  )

or

np.shape(  np.tile( np.tile(a, (n1,1)), (1,1,n2) )  )

I never obtain what I need, being the resulting shapes (n1, 1, len(a)*n3) or (1, n1, len(a)*n3). Maybe it is me not understanding how tile works ...

like image 460
gluuke Avatar asked Oct 02 '14 17:10

gluuke


People also ask

How do you make a NumPy 3d array?

Importing the NumPy package enables us to use the array function in python. To create a three-dimensional array, we pass the object representing x by y by z in python, where x is the nested lists in the object, y is the nested lists inside the x nested lists, and z is the values inside each y nested list.

What is tile function in NumPy?

The numpy.tile() function constructs a new array by repeating array – 'arr', the number of times we want to repeat as per repetitions. The resulted array will have dimensions max(arr.ndim, repetitions) where, repetitions is the length of repetitions.

Can NumPy arrays be multidimensional?

In general numpy arrays can have more than one dimension. One way to create such array is to start with a 1-dimensional array and use the numpy reshape() function that rearranges elements of that array into a new shape.

How do I repeat rows in NumPy?

NumPy: repeat() function The repeat() function is used to repeat elements of an array. Input array. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.


1 Answers

What's happening is that a is being made a 1x1x8 array before the tiling is applied. You'll need to make a a 1x8x1 array and then call tile.

As the documentation for tile notes:

If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.

The easiest way to get the result you're after is to slice a with None (or equivalently, np.newaxis) to make it the correct shape.

As a quick example:

import numpy as np

a = np.arange(8)
result = np.tile(a[None, :, None], (4, 1, 5))
print result.shape
like image 72
Joe Kington Avatar answered Sep 30 '22 20:09

Joe Kington