Reputation: 507
My dataframe has a column with list of dictionaries. How can i convert it into a extented dataframe? The dataframe is as shown.
A B C
123 abc [{"name":"john"},{"age":"28"},{"salary":"50000"}]
345 bcd [{"name":"alex"},{"age":"38"},{"salary":"40000"}]
567 xyx [{"name":"Dave"},{"age":"82"},{"salary":"30000"}]
I tried the following
> df1=pd.concat([pd.DataFrame(x) for x
> indf['C']],keys=df['A']).reset_index(level=1, drop=True).reset_index()
The Final output looks like
A B name salary age
123 abc john 50000 28
345 bcd alex 40000 38
567 xyx Dave 30000 82
Upvotes: 1
Views: 1255
Reputation: 323376
IIUC, flatten your list
of dict
s to one dict
, then we using dataframe constructor , and just need concat
back to original df
from itertools import chain
s=pd.DataFrame([dict(chain(*map(dict.items,x))) for x in df.pop('C').tolist()],index=df.index)
s
age name salary
0 28 john 50000
1 38 alex 40000
2 82 Dave 30000
s=pd.concat([df,s],1)
s
A B age name salary
0 123 abc 28 john 50000
1 345 bcd 38 alex 40000
2 567 xyx 82 Dave 30000
Data input :
df.to_dict()
{'A': {0: 123, 1: 345, 2: 567}, 'B': {0: 'abc', 1: 'bcd', 2: 'xyx'}, 'C': {0: [{'name': 'john'}, {'age': '28'}, {'salary': '50000'}], 1: [{'name': 'alex'}, {'age': '38'}, {'salary': '40000'}], 2: [{'name': 'Dave'}, {'age': '82'}, {'salary': '30000'}]}}
Upvotes: 2