Pandas DataFrame nunique() method with examples

Spread the love

The nunique() method in pandas Counts the number of distinct elements in specified axis.

Syntax –

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

axis – The axis to use. 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise.

dropna – Don’t include NaN in the counts.

Examples –

Let’s create a dataframe to work with.

import pandas as pd

data = {'Apple':[89, 89, 90, 110, 125, 84, 131, 123, 123, 140, 145, 145],
       'Orange': [46, 46, 50, 65, 63, 48, 110, 120, 60, 42, 47, 62],
       'Banana': [26, 30, 30, 25, 38, 22, 22, 36, 20, 27, 23, 34 ],
       'Mango': [80, 80, 90, 125, 130, 150, 140, 140, 135, 135, 80, 90]}

index = ['Jan','Feb','Mar','Apr','May','June','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame(data, index=index)
df

1 . Count Unique Values in Each Columns –

By Default, pandas count unique values in each columns as axis parameter is set to axis=0 or index.

df.nunique()
#output
Apple      9
Orange    11
Banana    10
Mango      7
dtype: int64

2. Count Unique values in Each Rows –

To count unique values in each rows set axis parameter to axis=1 or columns.

df.nunique(axis=1)
#output
Jan     4
Feb     4
Mar     3
Apr     4
May     4
June    4
Jul     4
Aug     4
Sep     4
Oct     4
Nov     4
Dec     4
dtype: int64

Rating: 1 out of 5.

Leave a Reply