Home > Net >  python - dataframe columns into dict of dicts
python - dataframe columns into dict of dicts

Time:03-30

I have a dataframe like:

subject   score_A   score_B   score_C
math        90        75        50
art         85        65        45
econ        90        80        60

I want to make them into a dict like:

{
   'math':{'A': 90,
           'B': 75,
           'C': 50},
   'art': {'A': 85,
           'B': 65,
           'C': 45},
   'econ':{'A': 90,
           'B': 80,
           'C': 60},
}

The actual dataframe is much longer and a bit wider (with more keys for each subject than A, B, and C).

I suppose this has something to do with generating list of lower-level keys like A, B, C, etc and using the zip function but none of my limited tries worked.

CodePudding user response:

You can set subject as index and then use to_dict with orient param -

df.set_index('subject').to_dict(orient='index')

CodePudding user response:

I guess you can use to_dict(). you can find the answer in the below link

Convert a Pandas DataFrame to a dictionary

  • Related