PAstudilloE
PAstudilloE

Reputation: 669

Convert dictionary of dictionaries into DataFrame Python

I am trying to convert the following dictionary of dictionaries into pandas DataFrame.

My dictionary looks like this:

mydata = {1965:{1:52, 2:54, 3:67, 4:45}, 
          1966:{1:34, 2:34, 3:35, 4:76}, 
          1967:{1:56, 2:56, 3:54, 4:34}} 

And I need to get a resulting dataframe that looks like this:

 Sector  1965  1966 1967
   1      52    34   56
   2      54    34   56
   3      67    35   54
   4      45    76   34

I was using something like this, but I'm not getting the result that I need.

df = pd.DataFrame([[col1,col2,col3] for col1, d in test.items() for col2, col3 in d.items()])enter code here

Thanks a lot for your help!!!

Upvotes: 4

Views: 1098

Answers (1)

jezrael
jezrael

Reputation: 862511

You can use DataFrame.from_records:

import pandas as pd

ydata = {1965:{1:52, 2:54, 3:67, 4:45}, 
          1966:{1:34, 2:34, 3:35, 4:76}, 
          1967:{1:56, 2:56, 3:54, 4:34}} 

print (pd.DataFrame.from_records(ydata))
   1965  1966  1967
1    52    34    56
2    54    34    56
3    67    35    54
4    45    76    34

print (pd.DataFrame.from_records(ydata).reset_index().rename(columns={'index':'Sector'}))
   Sector  1965  1966  1967
0       1    52    34    56
1       2    54    34    56
2       3    67    35    54
3       4    45    76    34

Upvotes: 5

Related Questions