3

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.

2 Answers2

4

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']}
kederrac
  • 16,819
  • 6
  • 32
  • 55
3

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']}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76