Pandas Series Series.nunique() Function

Pandas Series Series.nunique() Function

Jinku Hu Sep-17, 2020 May-30, 2020 Pandas Pandas Series
  1. Syntax of pandas.Series.nunique():
  2. Example Codes: Series.nunique() Method
  3. Example Codes: Series.nunique() Method With dropna=False

Python Pandas Series.nunique() method counts the unique values in the Python Pandas Series.

Syntax of pandas.Series.nunique():

Series.nunique(dropna=True)

Parameters

dropna True by default.
If True, NaN is excluded. If False, NaN is also counted.

Return

It returns an integer that counts the unique values in the caller Pandas Series.

Example Codes: Series.nunique() Method

import pandas as pd
import numpy as np

ser = pd.Series([1, 2, 3, np.nan, 3, 4, np.nan],
               name = 'No.')

print(ser.nunique())

Output:

4

The caller Series has 4 unique values - [1, 2, 3, 4] except NaN; therefore, Series.nunique() method returns 4 because NaN is excluded by default.

Example Codes: Series.nunique() Method With dropna=False

import pandas as pd
import numpy as np

ser = pd.Series([1, 2, 3, np.nan, 3, 4, np.nan],
               name = 'No.')

print(ser.nunique(dropna=False))

Output:

5

When dropna is False, NaN is also counted in Series.nunique() method.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

Related Article - Pandas Series

  • Pandas Series.head() Function
  • Pandas Series.to_frame() Function
  • Pandas Series.tolist() Function
  • Pandas Series Series.map() Function
  • Pandas Series Series.unique() Function