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'] }
python dictionary pandas group-by
Hypothetical Ninja
source share