排列python列表以形成三维numpy数组[duplicate]

lh80um4z  于 2023-03-08  发布在  Python
关注(0)|答案(2)|浏览(126)
    • 此问题在此处已有答案**:

Contruct 3d array in numpy from existing 2d array(4个答案)
5天前关闭。
我有五个列表,每个列表都相当于一个(4,3)形状的numpy数组,我想用下面提到的方式组合这些列表,得到一个(3,4,5)形状的numpy数组(x)。
以下是五个清单:

import numpy as np

x1 = [[1,11,111,111.1], [1111,11111,111111,111111.1], [0.1, 0.11, 0.111, 0.1111]]
x2 = [[2,22,222,222.2], [2222,22222,222222,222222.2], [0.2, 0.22, 0.222, 0.2222]]
x3 = [[3,33,333,333.3], [3333,33333,333333,333333.3], [0.3, 0.33, 0.333, 0.3333]]
x4 = [[4,44,444,444.4], [4444,44444,444444,444444.4], [0.4, 0.44, 0.444, 0.4444]]
x5 = [[5,55,555,555.5], [5555,55555,555555,555555.5], [0.5, 0.55, 0.555, 0.5555]]
    • 我希望组合数组(x)是这样的**
x[:, :, 0] is same as x1

x[:, :, 1] is same as x2

x[:, :, 2] is same as x3 

x[:, :, 3] is same as x4

x[:, :, 4] is same as x5
    • 如何获得上述功能?**

我已经试过x = np.array([x1, x2, x3, x4, x5]).reshape([3,4,5])了,但是这给了我:

x[:, :, 0] = array([[1.000000e+00, 1.111100e+04, 1.110000e-01, 2.222000e+02],
       [2.000000e-01, 3.300000e+01, 3.333330e+05, 3.333000e-01],
       [4.444000e+03, 4.400000e-01, 5.550000e+02, 5.555555e+05]])

当我想

x[:, :, 0] = array([[1, 11, 111, 111.1],
 [1111, 11111, 111111, 111111.1],
 [0.1, 0.11, 0.111, 0.1111]])
zqry0prt

zqry0prt1#

使用numpy.stack(沿最后一个维度连接数组序列):

x = np.stack([x1, x2, x3, x4, x5], axis=-1)
print(x[:, :, 2])

[[3.000000e+00 3.300000e+01 3.330000e+02 3.333000e+02]
 [3.333000e+03 3.333300e+04 3.333330e+05 3.333333e+05]
 [3.000000e-01 3.300000e-01 3.330000e-01 3.333000e-01]]
5ssjco0h

5ssjco0h2#

您需要执行以下操作:

x = np.array([np.array([*x]).T for x in zip(x1, x2, x3, x4, x5)])

结果

x[:, :, 0]
array([[1.000000e+00, 1.100000e+01, 1.110000e+02, 1.111000e+02],
       [1.111000e+03, 1.111100e+04, 1.111110e+05, 1.111111e+05],
       [1.000000e-01, 1.100000e-01, 1.110000e-01, 1.111000e-01]])

相关问题