Python:将2D数组重塑为3D数组

时间:2020-03-20 11:47:50

标签: python arrays numpy

我有以下2d数组abc

array([[-0.20152117, -1.44189064,  0.20784068],
       [ 0.47836196, -1.07317107, -0.17852614]])

我想将其转换为3d数组,使得结果为res[0,:,:]

请注意,此res[0]形状为3 x N,N = 10

array([[-0.20152117, -0.20152117, -0.20152117, ..., -0.20152117,
        -0.20152117, -0.20152117],
       [-1.44189064, -1.44189064, -1.44189064, ..., -1.44189064,
        -1.44189064, -1.44189064],
       [ 0.20784068,  0.20784068,  0.20784068, ...,  0.20784068,
         0.20784068,  0.20784068]])

并且res[1]的形状也是3xN

array([[ 0.47836196,  0.47836196,  0.47836196, ...,  0.47836196,
         0.47836196,  0.47836196],
       [-1.07317107, -1.07317107, -1.07317107, ..., -1.07317107,
        -1.07317107, -1.07317107],
       [-0.17852614, -0.17852614, -0.17852614, ..., -0.17852614,
        -0.17852614, -0.17852614]])

我该如何实现?

我尝试了(np.repeat(abc, 10, 0).reshape(2, 3, 10)),但这是错误的。

1 个答案:

答案 0 :(得分:0)

这是您要找的吗?

import numpy as np

abc = np.array([[-0.20152117, -1.44189064,  0.20784068],
              [ 0.47836196, -1.07317107, -0.17852614]])

N = 10
res = np.tile(abc.T, (N, 1, 1)).T
print(res[0])
print()
print(res[1])

收益

[[-0.20152117 -0.20152117 -0.20152117 -0.20152117 -0.20152117 -0.20152117
  -0.20152117 -0.20152117 -0.20152117 -0.20152117]
 [-1.44189064 -1.44189064 -1.44189064 -1.44189064 -1.44189064 -1.44189064
  -1.44189064 -1.44189064 -1.44189064 -1.44189064]
 [ 0.20784068  0.20784068  0.20784068  0.20784068  0.20784068  0.20784068
   0.20784068  0.20784068  0.20784068  0.20784068]]

[[ 0.47836196  0.47836196  0.47836196  0.47836196  0.47836196  0.47836196
   0.47836196  0.47836196  0.47836196  0.47836196]
 [-1.07317107 -1.07317107 -1.07317107 -1.07317107 -1.07317107 -1.07317107
  -1.07317107 -1.07317107 -1.07317107 -1.07317107]
 [-0.17852614 -0.17852614 -0.17852614 -0.17852614 -0.17852614 -0.17852614
  -0.17852614 -0.17852614 -0.17852614 -0.17852614]]