4

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

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.