While we have multiple Columns in our Dataframe, What if we need to count Unique values from a particular column? So in this tutorial, we are going to learn about How To Count unique values in a column in pandas dataframe? Let’s get started with this tutorial without wasting your time.
How To Count unique values in a column in pandas dataframe?
How To Count unique values in a column in pandas dataframe?
To Count unique values in a column in pandas dataframe You can Also Use pd.DataFrame.agg just like this. We are using the same example as I mentioned in method 1. Just put [‘count’, ‘size’, ‘nunique’] into pd.DataFrame.agg and it will return you total_count of the column, total_size of columns, and total_unique value count. Hope You understand. Thanks.
Count unique values in a column in pandas dataframe
To Count unique values in a column in pandas dataframe if I want to count unique values in a column in pandas dataframe then nunique we can Use. Just Use your Column name and put .unique() just like this: df[‘science’].nunique() And This is How we can Count the Unique value of the dataframe column. Thanks.
Method 1: Use nunique
Here, for example, I have the following data frame with marks.
df = pd.DataFrame({
'science': [97, 96, 95, 97, 96, 94, 96, 97],
'maths': [80, 81, 82, 79, 81, 83, 80, 79],
})
And if I want to count unique values in a column in pandas dataframe then nunique we can Use. Just Use your Column name and put .unique() just like this.
df['science'].nunique()
4
And This is How we can Count the Unique value of the dataframe column. Thanks.
Method 2: Use pd.DataFrame.agg
You can Also Use pd.DataFrame.agg just like this. We are using the same example as I mentioned in method 1.
df.agg(['count', 'size', 'nunique'])
science maths
count 8 8
size 8 8
nunique 4 5
Just put [‘count’, ‘size’, ‘nunique’] into pd.DataFrame.agg and it will return you total_count of the column, total_size of columns, and total_unique value count. Hope You understand. Thanks.
Method 3: Use this
Also You can Count unique values in a column in pandas dataframe using unique(). Just like this.
len(df.science.unique())
And it will return the Count of Unique value.
Conclusion
It’s all About this article. Hope this method worked for you. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?
Also, Read
- How To read data from google drive Using Google Colab?
- How To Find the difference between two data frames?
- How to Remove Conda environment in Python?
- How to clear react-native cache?
- ‘React’ must be in scope when using JSX react/react-in-jsx-scope