Signup/Sign In

Pandas DataFrame nunique() Method

In this tutorial, we will learn the Python pandas DataFrame.nunique() method. This method counts the number of distinct or unique observations over the requested axis. It returns Series with a number of distinct observations.

The below is the syntax of the DataFrame.nunique() method.

Syntax

DataFrame.nunique(axis=0, dropna=True)

Parameters

axis: It represents index or column axis, '0' for index and '1' for the column. When the axis=0, function applied over the index axis and when the axis=1 function applied over the column axis

dropna: It represents the bool(True or False), and the default is True. It doesn’t include NaN in the counts.

Example 1: Count unique values of the DataFrame

Here, in this example we will count the number of unique values in the DataFrame using the DataFrame.nunique() method. It returns the count, not the unique values.

#importing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1],'C': [2, 5, 5]})
print("------The DataFrame is-------")
print(df)
print("--------------------------------")
print(df.nunique(axis=0))


------The DataFrame is-------
A B C
0 1 1 2
1 2 1 5
2 3 1 5
--------------------------------
A 3
B 1
c 2
dtype: int64

Example 2: Count unique values of the DataFrame

This example is similar to the previous one, the DataFrame.nunique() method counts the unique values over the column axis.

#imporing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1],'c': [2, 5, 5]})
print("------The DataFrame is-------")
print(df)
print("--------------------------------")
print(df.nunique(axis=1))


------The DataFrame is-------
A B c
0 1 1 2
1 2 1 5
2 3 1 5
--------------------------------
0 2
1 3
2 3
dtype: int64

Example 3: Count unique values of the DataFrame

The DataFrame.nunique() method counts the null values as '0'. It means any column contains the null value then will be counted as 0. See the below example.

#imporing pandas as pd
import pandas as pd
df = pd.DataFrame({'A': [1, None, 3], 'B': [1, None, 1],'C': [2, None, 5]})
print("------The DataFrame is-------")
print(df)
print("--------------------------------")
print(df.nunique(axis=1))


------The DataFrame is-------
A B C
0 1.0 1.0 2.0
1 NaN NaN NaN
2 3.0 1.0 5.0
--------------------------------
0 2
1 0
2 3
dtype: int64

Conclusion

In this tutorial, we learned the Python pandas DataFrame.nunique() method. We learned the syntax, parameter and by applying this method on the DataFrame, we solved examples and understood the DataFrame.nunique() method.



About the author:
I like writing about Python, and frameworks like Pandas, Numpy, Scikit, etc. I am still learning Python. I like sharing what I learn with others through my content.