1

I'm trying to do a Pandas Groupby that counts the distinct value of the group by column and then uses that name to create a NamedAgg column with that name. For example:

animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],'color': ['red', 'black', 'red', 'yellow']})
animals

kind.     color
cat.      red
dog.      black
cat.      red
dog.      yellow

I tried using this code:

animals.groupby('kind').agg(
red=(animals['color']=='red', 'count'),
black=(animals['color']=='black', 'count'),
yellow=(animals['color']=='yellow', 'count'))

I wanted to get this result:

kind.     red.      black.      yellow
cat.       2
dog.                  1.         1

I researched and tried everything

sabic2003
  • 35
  • 4

0 Answers0