Arrange python lists so to form three dimensional numpy array

Question:

I have the five lists where each list is equivalent of a numpy array of shape (4,3). And, I want to combine these lists to get a numpy array (x) of shape (3,4,5) in the below mentioned fashion.

Here are the five lists:

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

I want the combined array (x) to be such that

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

How can I get the above functionality?

I have already tried x = np.array([x1, x2, x3, x4, x5]).reshape([3,4,5]). But this gives me:

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

when I want

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

||

Answers:

You need to do something like:

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

Result

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]])
Answered By: maciek97x

With numpy.stack (to join a sequence of arrays along the last dimension):

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]]
Answered By: RomanPerekhrest
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.