Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: constructing a 3D array from a 1D array

Tags:

arrays

numpy

Assume a 1D array A is given. Is there an easy way to construct a 3D array B, such that B[i,j,k] = A[k] for all i,j,k? You can assume that the shape of B is prescribed, and that B.shape[2] = A.shape[0].

like image 256
D R Avatar asked Apr 05 '11 23:04

D R


2 Answers

>>> k = 4
>>> a = np.arange(k)
>>> j = 3
>>> i = 2
>>> np.tile(a,j*i).reshape((i,j,k))
array([[[0, 1, 2, 3],
        [0, 1, 2, 3],
        [0, 1, 2, 3]],

       [[0, 1, 2, 3],
        [0, 1, 2, 3],
        [0, 1, 2, 3]]]
like image 199
Paul Avatar answered Sep 21 '22 13:09

Paul


Another easy way to do this is simple assignment -- broadcasting will automatically do the right thing:

i = 2
j = 3
k = 4
a = numpy.arange(k)
b = numpy.empty((i, j, k))
b[:] = a
print b

prints

[[[ 0.  1.  2.  3.]
  [ 0.  1.  2.  3.]
  [ 0.  1.  2.  3.]]

 [[ 0.  1.  2.  3.]
  [ 0.  1.  2.  3.]
  [ 0.  1.  2.  3.]]]
like image 31
Sven Marnach Avatar answered Sep 22 '22 13:09

Sven Marnach