Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a 3 dimensional list into a Dataframe?

I need to convert the following array into dataframe.

 import numpy as np
 import pandas as pd
 
 arr = [[0, [0.13, 0.24, 0.19]],
        [1, [0.10, 0.21, 0.06]],
        [2, [0.40, 0.29, 0.25]]]

 arr = np.array(arr, dtype=object)
 arr = pd.DataFrame(arr)
 print(arr)

The above code gives me the following output:

0                   1
0  0  [0.13, 0.24, 0.19]
1  1   [0.1, 0.21, 0.06]
2  2   [0.4, 0.29, 0.25]

But I would like to create the following dataframe from the array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   id  c_0  c_1  c_2
0  0  0.13 0.24 0.19
1  1   0.1 0.21 0.06
2  2   0.4 0.29 0.25

If anyone helps me to solve this problem, it is appreciated.

>Solution :

You can change the array that you convert to a DataFrame. This makes it possible to create a DataFrame like your output.

Only thing that is left is to change the column names.

import numpy as np
import pandas as pd

arr = [[0, [0.13, 0.24, 0.19]],
       [1, [0.10, 0.21, 0.06]],
       [2, [0.40, 0.29, 0.25]]]

arr = [[ele[0], *ele[1]] for ele in arr]

# No need to use numpy
# arr = np.array(arr, dtype=object)

arr = pd.DataFrame(arr)
columns = ['id', 'c_0', 'c_1', 'c_2']
arr.columns = columns 
print(arr)

   id   c_0   c_1   c_2
0   0  0.13  0.24  0.19
1   1  0.10  0.21  0.06
2   2  0.40  0.29  0.25

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading