search
Search
Unlock 100+ guides
search toc
close
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
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to
Pandas
655 guides
keyboard_arrow_down
check_circle
Mark as learned
thumb_up
0
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

# Pandas DataFrame | nunique method

schedule Aug 11, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
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. `axis`link | `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. `dropna`link | `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  C0  5  2  11  5  2  22  5  3  4 ```

## Counting column-wise

To count the number of unique numbers in each column:

``` df.nunique()   # axis=0 A  1B  2C  3dtype: 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 21 22 3dtype: 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    A0  NaN1  1.02  NaN ```

By default, `dropna=True`, which means that `NaN`s will be ignored:

``` df.nunique() A 1dtype: int64 ```

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

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

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

Edited by 0 others
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!