Create a dictionary from a groupby object, Python

Suppose I have a dataframe:

df = pd.DataFrame({'Type' : ['Pokemon', 'Pokemon', 'Bird', 'Pokemon', 'Bird', 'Pokemon', 'Pokemon', 'Bird'],'Name' : ['Jerry', 'Jerry', 'Flappy Bird', 'Mudkip','Pigeon', 'Mudkip', 'Jerry', 'Pigeon']}) 

and I group it by type:

 print df.groupby(['Type','Name'])['Type'].agg({'Frequency':'count'}) Frequency Type Name Bird Flappy Bird 1 Pigeon 2 Pokemon Jerry 3 Mudkip 2 

Can I create a dictionary from the above group? Key "Bird" will be the value of the list containing ['Pigeon',Flappy Bird'] , note that the name of the higher frequency should be displayed first in the Value list .

Expected Result:

 dict1 = { 'Bird':['Pigeon','Flappy Bird'] , 'Pokemon':['Jerry','Mudkip'] } 
+7
python dictionary pandas group-by
source share
1 answer

You can create a dictionary using a dictionary understanding as shown below.

 df = pd.DataFrame({'Type' : ['Pokemon', 'Pokemon', 'Bird', 'Pokemon', 'Bird', 'Pokemon', 'Pokemon', 'Bird'],'Name' : ['Jerry', 'Jerry', 'Flappy Bird', 'Mudkip','Pigeon', 'Mudkip', 'Jerry', 'Pigeon']}) f = df.groupby(['Type','Name'])['Type'].agg({'Frequency':'count'}) f.sort('Frequency',ascending=False, inplace=True) d = {k:list(f.ix[k].index) for k in f.index.levels[0]} print(d) # {'Bird': ['Pigeon', 'Flappy Bird'], 'Pokemon': ['Jerry', 'Mudkip']} 

Understanding the dictionary will go through the external index ("Bird", "Pokรฉmon"), and then set the value as the internal index for your dictionary.

First you need to sort the MultiIndex Frequency column to get the desired order.

+9
source share

All Articles