-1

I have a program that generating 2D arrays with different number of rows and appending them to list. I need to combine that list into one 3D array of 2D arrays.

A = np.zeros(15).reshape(3,5)
B = np.zeros(20).reshape(4,5)
C = np.zeros(25).reshape(5,5)
lst = [A, B, C]

[array([[0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]]), 
 array([[0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]]), 
 array([[0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]])]

Needs 3D array that looks like this

[[[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]] 
 [[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]
 [[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]]
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Full.Of.Life
  • 169
  • 2
  • 10

1 Answers1

1

Use the tolist method:

lst = [A.tolist(), B.tolist(), C.tolist()]

Or more generic:

lst_of_arrays = [A, B, C] # Could be initialized differently
lst = [ar.tolist() for ar in lst_of_arrays ]
Tawy
  • 579
  • 3
  • 14
  • Thx. But it makes list and I need 3D array. I tried np.array(lst), but it returns array of arrays. I read that it's same, but I want normal notation like '[[[ ]]]' not array([array([]), array([])]) ' – Full.Of.Life Apr 17 '20 at 13:25
  • 1
    Multidimensional numpy arrays are designed to have consistent dimensions across sub-arrays, because many operations would not make sense otherwise. Why do you need a 3D array instead of a list of 2D arrays or a 3D list? – Tawy Apr 17 '20 at 14:02
  • I don't know yet. I'm expecting that will be needed. I have plan to build observations from those arrays for OpenAI environment. And I will be transforming/coping/pasting parts of that 3D array to my new observation array. I thought that will be faster. – Full.Of.Life Apr 17 '20 at 14:36
  • Well, keeping your list of 2D arrays is probably the best thing to do until you encounter a good reason for reformatting the data. Come back then, but try to come up with a good reason why it would be significantly better to have a 3D array. Maybe you'll answer the problem by yourself ;) – Tawy Apr 17 '20 at 16:00
  • I recalled one reason. In that data there will be trading volume in columns and I want to use sum of all volume for normalization. – Full.Of.Life Apr 17 '20 at 17:59
  • Well, it is too vague for me to give you a reliable answer. Edit your question with more info e.g. what does A,B,C represent, what do you want to do with them etc..., so I can propose you a solution for your case (hint: it will most likely not involve a ndarray with variable sub-dimensions) – Tawy Apr 17 '20 at 18:49
  • Thx. Now when I know that it was not best idea, I'll handle it. Will do it in loop. Regards – Full.Of.Life Apr 17 '20 at 20:46