Home > Enterprise >  Convert Pandas dataframe with multiindex to a list of dictionaries
Convert Pandas dataframe with multiindex to a list of dictionaries

Time:12-01

I have a pandas dataframe, which looks like

     df = 
    Index1 Index2 Index3   column1  column2
     i11    i12    i13      2          5
     i11    i12    i23      3          8
     i21    i22    i23      4          5

How to convert this into list of dictionaries with keys as Index3, column1, column2 and values as in the respective cells.

So, expected output:

     [[{Index3: i13, column1: 2, column2: 5}, {Index3: i23, column1: 3, column2: 8}], [{Index3: i23, column1: 4, column2: 5}]]

Please note that the same values of Index1 and Index2 form 1 inner list and the values won't be repeated.

CodePudding user response:

d = {'Index1': ["i11", "i12", "i13"],  
     'Index2': ["i21", "i22", "i23"],      
     'Index3': ["i31", "i32", "i33"],      
     'column1': [2, 3,4],
     'column2': [5, 8, 5]}
df = pd.DataFrame(data=d)

This should fit:

a = []
for i in range(df.shape[0]):
    a.append({"Index3": df.iloc[2,i],"column 1": df.iloc[i,3], "column2": df.iloc[i,4]})

Res:

[{'Index3': 'i13', 'column 1': 2, 'column2': 5},
 {'Index3': 'i23', 'column 1': 3, 'column2': 8},
 {'Index3': 'i33', 'column 1': 4, 'column2': 5}]
  • Related