-1

Ok so I have this dictionary:

 {'a': [{'foo': '1'}, {'bar': '30'}],
 'b': [{'foo': '3'}],
 'c': [{'foo': '184'}, {'bar': '25'}],
 'd': [{'foo': '6'}],
 'e': [{'bar': '4'}],
 'f': [{'foo': '12'},{'bar': '1'}],
'name': 'brian'}

And I would like to transform it to a dataframe with multiindexing like this:

            a        b        c       d          e         f
         foo bar  foo bar  foo bar  foo bar    foo bar   foo bar
  brian  1   30    3   0   184  25   6   0     0    4     12   1

Any help?

Victor Serra
  • 21
  • 1
  • 3

1 Answers1

1

I'm guessing you'd have a bunch of those dicts where every name should go as index of the DataFrame. In that case you can do something like the following:

1.Retrieve the name and delete that from the dict original dict:

name = my_dict['name']
del my_dict['name']

2.Transform your dict to an appropiate shape:

 my_dict_exploded = {(k,innerk):innerv for k,v in my_dict.items() for element in v for innerk,innerv in element.items()}

df1 = pandas.DataFrame(my_dict_exploded,index=[name])

Your DataFrame will look like this:

        a       b   c        d   e   f    
      bar foo foo bar  foo foo bar bar foo
brian  30   1   3  25  184   6   4   1  12

This is similar to this other post: Nested dictionary to multiindex dataframe where dictionary keys are column labels where the answer by @BrenBarn is really useful.

VictorGGl
  • 1,848
  • 10
  • 15