I would like to use pandas groupby to count the occurrences of a combination of animals on each farm (denoted by the farm_id). I am trying to count the number of farms with each type of animal combination.
The desired output would be something like this:
Out[6]:
combo count
0 cow 1
1 [cow, chicken] 1
2 [cow, pig, chicken] 2
For the following dataframe:
df = pd.DataFrame([['cow',0],['chicken',0],
['cow',1],
['chicken',3],['pig',3],['cow',3],
['pig',4],['cow',4],['chicken',4]]
,columns=['animals','farm_id'])
df
Out[4]:
animals farm_id
0 cow 0
1 chicken 0
2 cow 1
3 chicken 3
4 pig 3
5 cow 3
6 pig 4
7 cow 4
8 chicken 4
Notice the order the animals appear does not matter.
I have tried this:
df.groupby('farm_id').agg({'animals':'unique'})
Out[7]:
animals
farm_id
0 [cow, chicken]
1 [cow]
3 [chicken, pig, cow]
4 [pig, cow, chicken]
Which gives me the combinations, but (1) the ordering is taken into account and (2) I'm not sure how to generate the count as a separate column.