0

I have an iterative procedure where I build a dictionary of dictionaries and I fill it with values.

d = {}
for i in data:
    d{i} = {}
    d[i]['day'] = {}
    d[i]['night'] = {}
    d[i]['day']['c1'] = ...
    d[i]['day']['c2'] = ...
    d[i]['day']['c3'] = ...
    d[i]['night']['c1'] = ...
    d[i]['night']['c2'] = ...
    d[i]['night']['c3'] = ...

I would like to to transform it into a multilevel dataframe.

The final result should be:

           day     |      night
-----------------------------------
       c1  c2  c3  |   c1  c2  c3
-----------------------------------
usa |  1   2   3   |   4   5   6
jap |  .   .   .   |   .   .   .
chi |  .   .   .   |   .   .   .
uk  |  .   .   .   |   .   .   .
ita |  .   .   .   |   .   .   .
ger |  .   .   .   |   .   .   .
rus |  .   .   .   |   .   .   .
sono
  • 266
  • 2
  • 7
  • 18

1 Answers1

0

This is the solution:

df = pd.concat({k: pd.DataFrame.from_dict(v, orient='columns') 
                 for k, v in d.items()}).unstack()

Credits: Convert nested dictionary to multilevel column dataframe

sono
  • 266
  • 2
  • 7
  • 18