search
Search
Publish
Guest 0reps
Thanks for the thanks!
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
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
A
A
share
thumb_up_alt
bookmark
arrow_backShare
thumb_up
0
thumb_down
0
chat_bubble_outline
0
auto_stories new
settings

# 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
expand_more

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

Count each column.

`0` or `"index"`

Count each row.

`1` or `"columns"`

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
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
A modern learning experience for data science and analytics