I have a dataframe df
in the format below, where content
is a string column.
JavaScript
x
4
1
content
2
0 {'api': ['api_1', 'api_1', 'api_1'],'A': [1,2,3], 'B': [4,5,6] }
3
1 {'api': ['api_2', 'api_2', 'api_2'],'A': [7,8,9], 'B': [10,11,12] }
4
and I want to convert it to the format:
JavaScript
1
8
1
api A B
2
0 api_1 1 4
3
1 api_1 2 5
4
2 api_1 3 6
5
3 api_2 7 10
6
4 api_2 8 11
7
5 api_2 9 12
8
I tried doing this,
JavaScript
1
2
1
pd.concat([pd.DataFrame(eval(row['content'])) for (rownum, row) in df.iterrows()])
2
which works, but it doesn’t look nice. Is there any better way to do this?
Advertisement
Answer
Let us try
JavaScript
1
9
1
out = pd.concat(pd.DataFrame(x) for x in df.content.map(literal_eval))
2
api A B
3
0 api_1 1 4
4
1 api_1 2 5
5
2 api_1 3 6
6
0 api_2 7 10
7
1 api_2 8 11
8
2 api_2 9 12
9