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)

>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)]

Leave a Reply