The nunique()
function in Pandas is used to compute the number of unique values in a dataframe or series. This can be useful for getting an overview of the data, or for identifying and removing duplicate values.
Here's an example of using the nunique()
function in Pandas to compute the number of unique values in a dataframe:
import pandas as pd
# create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3, 2, 3],
"B": [6, 7, 7, 8, 8]})
# compute the number of unique values in each column
df_nunique = df.nunique()
# display the result
print(df_nunique)
This will compute the number of unique values in each column of the dataframe, and return a new Series with the number of unique values in each column.
The output will be:
A 3
B 3
dtype: int64
You can also use the nunique()
function to compute the number of unique values in a particular column or row of a dataframe. For example:
# compute the number of unique values in the A column
col_a_nunique = df["A"].nunique()
# display the result
print(col_a_nunique)
This will compute the number of unique values in the A
column of the dataframe, and return a single integer value.
The output will be:
3
The nunique()
function is useful for computing the number of unique values in a dataframe or series, and it can be used to get an overview of the data or to identify and remove duplicate values.
Related tutorials curated for you
What is isna() in Pandas?
How to reshape a Pandas DataFrame
How to get the first row in Pandas
What does factorize() do in Pandas?
How to add an empty column to a Pandas DataFrame
How to create a bar chart in Pandas
How to calculate covariance in Pandas
How to groupby mean in Pnadas
What does Head() do in Pandas?
How to drop an index column in Pandas
Pandas read SQL
How to sort a series in Pandas