From dic pandas with nested dictionaries

Viewed 70

I have a dictionary like that:

{12: {'Soccer': {'value': 31, 'year': 2013}},
 23: {'Volley': {'value': 24, 'year': 2012},'Yoga': {'value': 3, 'year': 2014}},
39: {'Baseball': {'value': 2, 'year': 2014},'basket': {'value': 4, 'year': 2012}}}

and i would like to have a dataframe like this:

index                      column     
12         {'Soccer': {'value': 31, 'year': 2013}}
23         {'Volley': {'value': 24, 'year': 2012},'Yoga': {'value': 3, 'year': 2014}}
39         {'Baseball': {'value': 2, 'year': 2014},'basket': {'value': 4, 'year': 2012}}

with each nested dictionary set in a unique column, with the row given by the key of the external dictionary. When I use 'from_dict' with orient parameter equal to index, it considers that keys from the nested dictionaries are the labels of the columns and it makes a square dataframe instead of a single column... Thanks a lot

2 Answers

Use:

df = pd.DataFrame({'column':d})

Or:

df = pd.Series(d).to_frame('column')

print (df)
                                               column
12            {'Soccer': {'year': 2013, 'value': 31}}
23  {'Volley': {'year': 2012, 'value': 24}, 'Yoga'...
39  {'Baseball': {'year': 2014, 'value': 2}, 'bask...
In [65]: pd.DataFrame(d.values(), index=d.keys(), columns=['column'])
Out[65]:
                                               column
12  ({'Soccer': {'value': 31, 'year': 2013}}, {'Vo...
23  ({'Soccer': {'value': 31, 'year': 2013}}, {'Vo...
39  ({'Soccer': {'value': 31, 'year': 2013}}, {'Vo...
Related