Ratha
Ratha

Reputation: 9692

How to count when a column has unique values in pandas?

My file contains a column called 'Id';

eg:

Id  bill
---------
1   aaa
2   bbb
3   ccc
1   ddd
2   ee

I would like to return the count of Ids. Here it should be count(data['Id')) = 3 (not 5)

print(df.groupby('Id').count()) prints the whole file with rows count and column count. How can I make sure simple it prints how many unique Ids present in the column?

Upvotes: 0

Views: 53

Answers (3)

jezrael
jezrael

Reputation: 862641

Use Series.nunique:

a = df["Id"].nunique()
print (a)
3

Or convert values to sets and get length:

a = len(set(df["Id"]))
print (a)
3

Upvotes: 2

san
san

Reputation: 1515

In your original attempt just use the length of the returned dataframe using len()

print(len(df.groupby('Id').count()))

Upvotes: 1

meTchaikovsky
meTchaikovsky

Reputation: 7666

You can also use collections.Counter, assume tmp is your dataframe

from collections import Counter

count = Counter(tmp['Id'])

Upvotes: 1

Related Questions