I have a pandas data frame as such
**Breed Animal**
Orange Tab Cat
Tuxedo Cat
Tabby Cat
Husky Dog
Golden Dog
Labrador Dog
Poodle Dog
Koi Fish
Fantail Fish
GoldFish Fish
and would like to create a dictionary as such
mydict = {
"Cat": ['Orange Tab', 'Tuxedo', 'Tabby'],
"Dog": ['Husky','Golden','Labrador','Poodle'],
"Fish": ['Koi','Fantail','GoldFish']
}
I have never dealt with dictionary with Pandas data frame so I have no idea where to start. I imagine I have to use a nested for loop but have no idea how to loop through the Animal part in the data frame.
Thanks in advance.
you can use pandas.DataFrame.groupby:
df.groupby('Animal**')['**Breed'].agg(list).to_dict()
output:
{'Cat': ['Orange Tab', 'Tuxedo', 'Tabby'],
'Dog': ['Husky', 'Golden', 'Labrador', 'Poodle'],
'Fish': ['Koi', 'Fantail', 'GoldFish']}
Use groupby with list and then convert to dictionary:
result = df.groupby('Animal')['Breed'].apply(list)
print(result.to_dict())
Output
{'Cat': ['Orange Tab', 'Tuxedo', 'Tabby'], 'Dog': ['Husky', 'Golden', 'Labrador', 'Poodle'], 'Fish': ['Koi', 'Fantail', 'GoldFish']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With