0

I wish to convert

edit : the code below is a 3D list of list,

[
    [ 
        [
            [1,2,3,],
            [4,5,6,],
        ],
        [
            [7,8,9,],
            [10,11,12,], 
        ],
    ],
    [ 
        [
            [A,B,C,],
            [D,E,F,], 
        ],
        [
            [G,H,I,],
            [J,K,L,], 
        ],
    ],
]

Into

[

[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12],
[A,B,C],
[D,E,F],
[G,H,I],
[J,K,L]

]

I have tried numpy.flatten but with no success https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html

3
  • 1
    Have you tried my_array.reshape(8, 3)? Commented Apr 23, 2019 at 12:01
  • Since you have characters and numbers in your list, I recommend using pandas instead of numpy Commented Apr 23, 2019 at 14:25
  • What dtype do you want? What are A, B etc. As shown those are variables, not strings. As such they must have values, which in Python could be anything. Variable ids won't display in the actual list (or array). Commented Apr 23, 2019 at 16:31

1 Answer 1

2

Reshape is your tool.

Here is a self contained example:

import numpy as np
a = np.array([
    [[[1,2,3] , [4,5,6]],
     [[7,8,9] , [10,11,12]]],
    [[[13,14,15] , [16,17,18]],
     [[19,20,21] , [22,23,24]]]
    ])

a.shape
>>> (2, 2, 2, 3)

a.reshape(8,3)
>>> array([[ 1,  2,  3],
>>>        [ 4,  5,  6],
>>>        [ 7,  8,  9],
>>>        [10, 11, 12],
>>>        [13, 14, 15],
>>>        [16, 17, 18],
>>>        [19, 20, 21],
>>>        [22, 23, 24]])
Sign up to request clarification or add additional context in comments.

4 Comments

or a.reshape(-1,3) if you don't want to pre-calculate the number of rows.
Thanks Jurgen and @Dan . but I found that my code is a 3D list of lists, not a 3D array. I edited my question : how to convert 3D lit of list into a 2D array.
@BrigitteCharpent you can use np.array() and list to convert between the two and still use this method
Thanks to all of you. I had difficulties transforming eachlist level into an array level. Finally I simply iterated over my lists in plain simple Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.