Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe to dict grouping by column

I have a dataframe like this:

Subject_id    Subject    Score    
Subject_1        Math        5                 
Subject_1    Language        4                 
Subject_1       Music        8
Subject_2        Math        8                 
Subject_2    Language        3                 
Subject_2       Music        9

And I want to convert it into a dictionary, grouping by subject_id

{'Subject_1': {'Math': 5,
               'Language': 4,
               'Music': 8},
{'Subject_2': {'Math': 8,
               'Language': 3,
               'Music': 9}
}

If I would have only one Subject, then I could so:

my_dict['Subject_1'] = dict(zip(df['Subject'],df['Score']))

But since I have several subjects the list of keys repeats, so I cannot use directly a zip.

Dataframes has a .to_dict('index') method but I need to be able to group by a certain column when creating the dictionary.

How could I achieve that?

Thanks.

like image 898
Sembei Norimaki Avatar asked Jan 11 '18 13:01

Sembei Norimaki


1 Answers

Use groupby with custom lambda function and last convert output Series to_dict:

d = (df.groupby('Subject_id')
       .apply(lambda x: dict(zip(x['Subject'],x['Score'])))
       .to_dict())

print (d)
{'Subject_2': {'Math': 8, 'Music': 9, 'Language': 3}, 
 'Subject_1': {'Math': 5, 'Music': 8, 'Language': 4}}

Detail:

print (df.groupby('Subject_id').apply(lambda x: dict(zip(x['Subject'],x['Score']))))

Subject_id
Subject_1    {'Math': 5, 'Music': 8, 'Language': 4}
Subject_2    {'Math': 8, 'Music': 9, 'Language': 3}
dtype: object
like image 81
jezrael Avatar answered Oct 11 '22 14:10

jezrael