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 unique values considering column

I have a df as the following:

col1  col2
-----------
a      1b
a      1b
a      1a
b      2a
b      3f

And I want to count how many unique pairs each col1 element has:
output:

(a, 2)
(b, 2)

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 :

You want to count the number if unique values on col2 after grouping on col1

df.groupby(['col1']).nunique()['col2']
#col1
#a    2
#b    2

If you want it in the format you mentioned, you can pass it into zip

list(zip(df.groupby(['col1']).nunique()['col2'].index, df.groupby(['col1']).nunique()['col2'].values))                           
[('a', 2), ('b', 2)]
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