1

df:

Field1 Field2
1      2
3      4
5      6
1      7
3      8

Please let me know how to find distinct count of df['Field1'], Results should be 3 In SQL we use query like this.

select count(distinct Field1) as Field1DistCount from df
Scott Boston
  • 133,446
  • 13
  • 126
  • 161
Learnings
  • 2,450
  • 5
  • 30
  • 47
  • Possible duplicate of [Count unique values with pandas](https://stackoverflow.com/questions/38309729/count-unique-values-with-pandas) – Thomas Dussaut Jul 05 '17 at 14:32

3 Answers3

3

Let's use nunique:

df['Field1'].nunique()

Output:

3
Scott Boston
  • 133,446
  • 13
  • 126
  • 161
2

I'm assuming you are using pandas?

import pandas as pd
print(df['COLUMN_NAME_HERE'].nunique())

If you want a dataframe of the unique values you could do (and here is a good link to go along with it):

print(df['COLUMN_NAME_HERE'].unique())

And if you want the counts of those unique values using value_counts:

print(df['COLUMN_NAME_HERE'].value_counts())
MattR
  • 4,508
  • 9
  • 37
  • 62
0

You can even use value_counts() to get the count of unique values for a particular value present in a column.

Example :

df['col_name'].value_counts().values #This will fetch you the count

And if you want to store the unique values in another column then you can execute the below command :

df['col_name'].value_counts().index

Let me know if this helps. Thanks

JKC
  • 2,348
  • 4
  • 28
  • 53