I have a dataframe which has a list of dictionaries as a column: This column has the following format:
JavaScript
x
2
1
[{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '2'}]
2
How can I convert this column into 4 new columns? I mean: route_id (x2), stop_id(x2) as new columns.
Thanks in advance!
Advertisement
Answer
You can use df.explode
with df.apply
:
JavaScript
1
13
13
1
In [275]: df = pd.DataFrame({'A': [[{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '2'}]]})
2
3
In [276]: df
4
Out[276]:
5
A
6
0 [{'route_id': '1', 'stop_id': '1'}, {'route_id...
7
8
In [284]: df['A'].explode().apply(pd.Series)
9
Out[284]:
10
route_id stop_id
11
0 1 1
12
0 2 2
13