简体   繁体   中英

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!!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM