search
Search
Publish
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
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
A
A
share
thumb_up_alt
bookmark
arrow_backShare
Twitter
Facebook

Pandas DataFrame | nunique method

Programming
chevron_right
Python
chevron_right
Pandas
chevron_right
Documentation
chevron_right
DataFrame
chevron_right
Basic and Descriptive Statistics
schedule Mar 9, 2022
Last updated
local_offer PythonPandas
Tags

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

Count each column.

0 or "index"

Count each row.

1 or "columns"

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
Ask a question or leave a feedback...