Home > other >  Nested dictionary to multiindex dataframe
Nested dictionary to multiindex dataframe

Time:07-01

I'm trying to convert a nested dictionary to multiindex dataframe where dictionary keys are columns labels.

my_dict = {"season":"summer", "threshold":70, "analysis" : {"max_temp":50, "min_temp":20}}

I followed the code which is linked to this question Nested dictionary to multiindex dataframe where dictionary keys are column labels but I've got an error AttributeError: 'str' object has no attribute 'items'

The following code:

reform = {(outerKey, innerKey): values for outerKey, innerDict in my_dict.items() for innerKey, values in innerDict.items()}

Could anyone help me to solve this issue?

Thanks in advance

CodePudding user response:

IIUC, try:

my_dict = {"season":"summer", "threshold":70, "analysis" : {"max_temp":50, "min_temp":20}}

df_in = pd.json_normalize(my_dict)

df_in.columns = df_in.columns.str.split('.', expand=True)

df_in

Output:

   season threshold analysis         
      NaN       NaN max_temp min_temp
0  summer        70       50       20
  • Related