Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: Convert nested dictionary to dataframe

I have a dic like this:

{1 : {'tp': 26, 'fp': 112},
2 : {'tp': 26, 'fp': 91},
3 : {'tp': 23, 'fp': 74}}

and I would like to convert in into a dataframe like this:

t tp fp
1 26  112
2 26  91
3 23  74

Does anybody know how?

like image 281
UserYmY Avatar asked Jul 16 '15 16:07

UserYmY


2 Answers

Try DataFrame.from_dict() and with keyword argument orient as 'index' -

Example -

In [20]: d = {1 : {'tp': 26, 'fp': 112},
   ....: 2 : {'tp': 26, 'fp': 91},
   ....: 3 : {'tp': 23, 'fp': 74}}

In [24]: df =pd.DataFrame.from_dict(d,orient='index')

In [25]: df
Out[25]:
   tp   fp
1  26  112
2  26   91
3  23   74

If you also want to set the column name for index column , use - df.index.name , Example -

In [30]: df.index.name = 't'

In [31]: df
Out[31]:
   tp   fp
t
1  26  112
2  26   91
3  23   74
like image 133
Anand S Kumar Avatar answered Oct 12 '22 18:10

Anand S Kumar


I just wanted to note (as this is one of the top results for converting from a nested dictionary to a pandas dataframe) that there are other ways of nesting dictionaries that can be also be converted to a dataframe (e.g. nesting via columns).

e.g. the following nested dictionary

patients = {"Name":{"0":"John","1":"Nick","2":"Ali","3":"Joseph"},
            "Gender":{"0":"Male","1":"Male","2":"Female","3":"Male"},
            "Nationality":{"0":"UK","1":"French","2":"USA","3":"Brazil"},
            "Age" :{"0":10,"1":25,"2":35,"3":29}}

can be converted to a pandas dataframe using orient='columns'

df_patients = pd.DataFrame.from_dict(patients, orient='columns')

like image 4
djproc Avatar answered Oct 12 '22 16:10

djproc