Skip to content
Advertisement

How to convert a list with dictionaries into new pandas columns?

I have a dataframe which has a list of dictionaries as a column: This column has the following format:

[{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '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:

In [275]: df = pd.DataFrame({'A': [[{'route_id': '1', 'stop_id': '1'}, {'route_id': '2', 'stop_id': '2'}]]})

In [276]: df
Out[276]: 
                                                   A
0  [{'route_id': '1', 'stop_id': '1'}, {'route_id...

In [284]: df['A'].explode().apply(pd.Series)
Out[284]: 
  route_id stop_id
0        1       1
0        2       2
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement