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].
A
B
B[i,j,k] = A[k]
B.shape[2] = A.shape[0]
>>> 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]]]
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.]]]
for k,v in enumerate(A): B[:,:,k] = v