Home > Blockchain >  How to convert a 3 dimensional list into a Dataframe?
How to convert a 3 dimensional list into a Dataframe?

Time:01-15

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:

   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.

CodePudding user response:

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

  •  Tags:  
  • Related