Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas, count rows per unique value

I have a pandas dataframe like this:

    c1  c2  
0   A   red
1   B   blue
2   B   blue
3   C   red
4   C   red
5   C   blue
6   D   blue

All I want to do is find out how many red/blue values there are per all values in c1. Something like this:

    red  blue
A   1    0
B   0    2  
C   2    1
D   0    1

I tried using masks and groupby() but failed coming up with a solution. The main reason is that I am not allowed to use loops. Feels like there is an obvious solution but I’m not that good at using pandas :/ Any advice?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Simple groupby with value_counts.

df.groupby('c1')['c2'].value_counts().unstack(fill_value=0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading