Python | Pandas Index.nunique()

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output :

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


Output :

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.