简体   繁体   中英

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?

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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM