count unique groupby pandas code example

Example 1: pandas groupby column count distinct values

# Pandas group by a column looking at the count unique/count distinct values of another column

df.groupby('param')['group'].nunique()

Example 2: count unique pandas

df['column'].nunique()

Example 3: pandas groupby count unique rows

df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
    domain  ID
0       fb   1
1      ggl   1
2  twitter   2
3       vk   3

Example 4: pandas groupby count unique rows

ID, domain
123, 'vk.com'
123, 'vk.com'
123, 'twitter.com'
456, 'vk.com'
456, 'facebook.com'
456, 'vk.com'
456, 'google.com'
789, 'twitter.com'
789, 'vk.com'

Example 5: group by pandas count

df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])