Open In App

Python | Pandas Index.nunique()

Last Updated : 18 Dec, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas Index.nunique() function return number of unique elements in the object. It returns a scalar value which is the count of all the unique values in the Index. By default the NaN values are not included in the count. If dropna parameter is set to be False then it includes NaN value in the count.

Syntax: Index.nunique(dropna=True)

Parameters :
dropna : Don’t include NaN in the count.

Returns : nunique : int

Example #1: Use Index.nunique()() function to find the count of unique values in the Index. Do not include NaN values in the count.




# importing pandas as pd
import pandas as pd
  
# Creating the index
idx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug',
                        'Mastiff', None, 'Beagle'])
  
# Print the Index
idx


Output :

Let’s find the count of unique values in the Index.




# to find the count of unique values.
idx.nunique(dropna = True)


Output :

As we can see in the output, the function has returned 4 indicating that there are only 4 unique values in the Index.
 
Example #2: Use Index.nunique() function find out all the unique values in the Index. Also include the missing values i.e. NaN values in the count.




# importing pandas as pd
import pandas as pd
  
# Creating the index
idx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Pug',
                        'Mastiff', None, 'Beagle'])
  
# Print the Index
idx


Output :

Let’s find the count of unique values in the Index.




# to find the count of unique values.
idx.nunique(dropna = False)


Output :

As we can see in the output, the function has returned 5 indicating that there are only 5 unique values in the Index. We have also included the missing values in the count.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads