Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build Python dictionary from Pandas columns using loop [duplicate]

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.

like image 728
user10969675 Avatar asked Dec 17 '25 19:12

user10969675


2 Answers

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']}
like image 52
kederrac Avatar answered Dec 20 '25 10:12

kederrac


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']}
like image 27
Dani Mesejo Avatar answered Dec 20 '25 11:12

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!