Numpy:从一维数组构建一个3D数组

时间:2022-09-03 21:40:51

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].

假设给出1D阵列A.是否有一种简单的方法来构建一个3D数组B,使得所有i,j,k的B [i,j,k] = A [k]?你可以假设B的形状是规定的,而B.shape [2] = A.shape [0]。

3 个解决方案

#1


8  

>>> 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]]]

#2


3  

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.]]]

#3


0  

for k,v in enumerate(A): B[:,:,k] = v

#1


8  

>>> 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]]]

#2


3  

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.]]]

#3


0  

for k,v in enumerate(A): B[:,:,k] = v