Having a data as below:
JavaScript
x
3
1
mylist=[((10, 'L5', ['abc']), 0),
2
((15, 'L6', ['bda', 'LAS']), 5)]
3
I need to convert this data to data frame. I need the dataframe/output as follows:
COL1 | COL2 | COL3 | COL4 |
---|---|---|---|
10 | L5 | [‘abc’] | 0 |
15 | L6 | [‘bda’, ‘LAS’] | 5 |
Advertisement
Answer
You could use tuple unpacking in a comprehension:
JavaScript
1
12
12
1
In [1]: import pandas as pd
2
In [2]: my_data = [((10, 'L5', ['abc']), 0), ((15, 'L6', ['bda', 'LAS']), 5)]
3
In [3]: new_my_data = [[col1, col2, col3, col4] for ((col1, col2, col3), col4) in my_data]
4
In [4]: new_my_data
5
Out[4]: [[10, 'L5', ['abc'], 0], [15, 'L6', ['bda', 'LAS'], 5]]
6
In [5]: df = pd.DataFrame(new_my_data, columns=['COL1', 'COL2', 'COL3', 'COL4'])
7
df :
8
Out[5]:
9
COL1 COL2 COL3 COL4
10
0 10 L5 [abc] 0
11
1 15 L6 [bda, LAS] 5
12