Skip to content Skip to sidebar Skip to footer

Dict Of Dict Of Dicts To Pandas Dataframe - Changing Multiindex Rows To Be Columns

I have a dictionary like this: my_dict = {'Key': {'Service': {'Number': 61, 'Percent': 2.54 }, 'Service2': {'Number': 42, 'Percent': 2.2 } }, 'Key2': {'Service3': {'Number': 8, 'Pe

Solution 1:

pd.concat({k: pd.DataFrame(v) for k, v in my_dict.items()})

              Service  Service2  Service3
Key  Number     61.00      42.0       NaN
     Percent     2.54       2.2       NaN
Key2 Number       NaN      52.0      8.00
     Percent      NaN       2.5      2.74

pd.concat({k: pd.DataFrame(v) for k, v in my_dict.items()}, axis=1).stack(0).T

         Number       Percent      
            Key  Key2     Key  Key2
Service    61.0   NaN    2.54   NaN
Service2   42.0  52.0    2.20  2.50
Service3    NaN   8.0     NaN  2.74

This doesn't rely on comprehensions

pd.DataFrame(my_dict).stack().apply(pd.Series).unstack()
# pandas.DataFrame(i).stack().apply(pandas.Series).unstack()

         Number       Percent      
            Key  Key2     Key  Key2
Service    61.0   NaN    2.54   NaN
Service2   42.0  52.0    2.20  2.50
Service3    NaN   8.0     NaN  2.74

Post a Comment for "Dict Of Dict Of Dicts To Pandas Dataframe - Changing Multiindex Rows To Be Columns"