Numpy: building a three-dimensional array from a 1D array

Suppose a 1D array is given A. Is there an easy way to build a three-dimensional array Bsuch that B[i,j,k] = A[k]for all i, j, k? You can assume that Form B is prescribed, and that B.shape[2] = A.shape[0].

+5
source share
3 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]]]
+8
source

Another easy way to do this is with a simple assignment - the broadcast 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.]]]
+3
source
for k,v in enumerate(A): B[:,:,k] = v
0
source

All Articles