0

I have a dataframe that contains as follows:

  A   B  
1 Cat 1
2 Cat 2
3 Dog 1
4 Dog 2
5 Dog 3
6 Dog 4

I want to create a dictionary like this with the above dataframe: {'Cat':[1,2], 'Dog':[1,2,3,4]} Can anyone shed some insight on this? Thank you.

kimhkh
  • 27
  • 4

1 Answers1

0

Use groupby() method , apply() method and to_dict() method:

result=df.groupby('A')['B'].apply(list).to_dict()

Now if you print result you will get your desired output:

{'Cat': [1, 2], 'Dog': [1, 2, 3, 4]}
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41