This question already has an answer here:
- Pandas count(distinct) equivalent 4 answers
I need to count unique ID
values in every domain
I have data
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'
I try df.groupby(['domain', 'ID']).count()
But I want to get
domain, count
vk.com 3
twitter.com 2
facebook.com 1
google.com 1
Generally to count distinct values in single column, you can use
Series.value_counts
:To see how many unique values in a column, use
Series.nunique
:To get all these distinct values, you can use
unique
ordrop_duplicates
, the slight difference between the two functions is thatunique
return anumpy.array
whiledrop_duplicates
returns apandas.Series
:As for this specific problem, since you'd like to count distinct value with respect to another variable, besides
groupby
method provided by other answers here, you can also simply drop duplicates firstly and then dovalue_counts()
:IIUC you want the number of different
ID
for everydomain
, then you can try this:output:
You could also use
value_counts
, which is slightly less efficient.But the best is Jezrael's answer usingnunique
:df.domain.value_counts()
You need
nunique
:If you need to
strip
'
characters:Or as
Jon Clements
commented:You can retain the column name like this:
The difference is that
nunique()
returns a Series andagg()
returns a DataFrame.