Home > Enterprise >  How to group by one axis, count elements of another one and create a new dimension with it
How to group by one axis, count elements of another one and create a new dimension with it

Time:11-27

I have the following pandas dataframe df

         time  animal
0           0    cat
1           0    dog
2           1    hedgehog
3           1    cat
4           1    cat

I would like to

  • group by time while counting how often an animal is withing the new group, like 2x cat at time 1.
  • create a 2nd dimension for the count values then.

like that:

animal   cat  dog  hedgehog
time
  0       1    1      0
  1       2    0      1

Any ideas how to accomplish that?

CodePudding user response:

Try pd.crosstab:

print(pd.crosstab(df.time, df.animal))

Prints:

animal  cat  dog  hedgehog
time                      
0         1    1         0
1         2    0         1

CodePudding user response:

As per Andrej Kesely in his answer's enter image description here

  • Related