Timmy O'Mahony
Timmy O'Mahony

Reputation: 53971

Convert (MultiIndex) Dataframe to a list of dicts

I have a multi index dataframe:

                       C
 A         B
25        58        16.0
          59       135.0
          60        36.0

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

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

I am able to 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 a simple way to achieve this?

Upvotes: 3

Views: 627

Answers (1)

piRSquared
piRSquared

Reputation: 294218

use to_dict with 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}]

Upvotes: 7

Related Questions