Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From dic pandas with nested dictionaries

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

like image 934
phil Avatar asked Dec 13 '25 17:12

phil


1 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...
like image 173
jezrael Avatar answered Dec 16 '25 18:12

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!