search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Pandas DataFrame | nunique method

schedule Aug 11, 2023
Last updated
local_offer
PythonPandas
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Pandas DataFrame.nunique(~) method counts the number of unique values for each row or column in the DataFrame.

Parameters

1. axislink | int or string

The axis along which to count the number of unique values:

Value

Meaning

0 or "index"

Count each column.

1 or "columns"

Count each row.

By default, axis=0.

2. dropnalink | boolean | optional

Whether or not to ignore NaN. By default, dropna=True.

Return Value

A Series that holds the count of unique numbers in each row or column of the source DataFrame.

Examples

Consider the following DataFrame:

df = pd.DataFrame({"A":[5,5,5], "B":[2,2,3], "C":[1,2,4]})
df
   A  B  C
0  5  2  1
1  5  2  2
2  5  3  4

Counting column-wise

To count the number of unique numbers in each column:

df.nunique()   # axis=0
A  1
B  2
C  3
dtype: int64

This tells us that:

  • column A has 1 unique value.

  • column B has 2 unique values.

  • column C has 3 unique values.

Counting row-wise

To count the number of unique numbers in each row, set axis=1:

df.nunique(axis=1)
0 2
1 2
2 3
dtype: int64

This tells us that:

  • row 0 has 2 unique values.

  • row 1 has 2 unique values.

  • row 2 has 3 unique values.

Dealing with missing values

Consider the following DataFrame with two missing values:

df = pd.DataFrame({"A":[np.NaN,1,np.NaN]})
df
   A
0  NaN
1  1.0
2  NaN

By default, dropna=True, which means that NaNs will be ignored:

df.nunique()
A 1
dtype: int64

We can consider them as values by setting dropna=False:

df.nunique(dropna=False)
A 2
dtype: int64

This tell us that column A has 2 unique values: NaN and 1.0.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!