Pandas Tutorial Pandas References

Pandas Series - nunique() function



The Pandas Series nunique() function returns number of unique elements in the Series.

Syntax

Series.nunique(dropna=True)

Parameters

dropna Optional. Specify False to include NaN in the counts. Default is True.

Return Value

Returns number of unique elements in the Series.

Example: using nunique() on a Series

In the example below, the nunique() function is used to get the count of distinct elements in the series.

import pandas as pd
import numpy as np

x = pd.Series([10, 5, 5, 10, 5])

print("The Series contains:")
print(x)

#getting the count of distinct 
#elements in the series
print("\nx.nunique() returns:")
print(x.nunique())

The output of the above code will be:

The Series contains:
0    10
1     5
2     5
3    10
4     5
dtype: int64

x.nunique() returns:
2

Example: using nunique() on selected series in a DataFrame

Similarly, the nunique() function can be applied on selected series/column of a given DataFrame. Consider the following example.

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "x": [5, 5, 2, 2, 7],
  "y": [10, 5, 5, 10, 5],
  "z": [1, 1, 1, 1, 1]},
  index= ["a", "b", "c", "d", "e"]
)

print("The DataFrame is:")
print(df)

#count of distinct elements in 'x' series
print("\ndf['x'].nunique() returns:")
print(df["x"].nunique())

The output of the above code will be:

The DataFrame is:
   x   y  z
a  5  10  1
b  5   5  1
c  2   5  1
d  2  10  1
e  7   5  1

df['x'].nunique() returns:
3

❮ Pandas Series - Functions

5