Converting (MultiIndex) Dataframe to dicts list

I have a multi-frame data frame:

                       C
 A         B
25        58        16.0
          59       135.0
          60        36.0

      

which I want to convert to a dicts / objects list:

[
     {A: 25, B: 58, C: 16},
     {A: 25, B: 59, C: 135},
     {A: 25, B: 60, C: 36}
]

      

I can reset the index df.reset_index

:

           A        B      C
0         25       58   16.0
1         25       59  135.0
2         25       60   36.0

      

and use df.to_dict('index')

to get this:

[
     {0: {A: 25, B: 58, C: 16}},
     {1: {A: 25, B: 59, C: 135}},
     {2: {A: 25, B: 60, C: 36}}
]

      

which is close, but I don't want to include the index in the resulting dict.

Is there an easy way to achieve this?

+3


source to share


1 answer


use with to_dict

records



df.reset_index().to_dict('records')

[{'A': 25.0, 'B': 58.0, 'C': 16.0},
 {'A': 25.0, 'B': 59.0, 'C': 135.0},
 {'A': 25.0, 'B': 60.0, 'C': 36.0}]

      

+6


source







All Articles