ADVERTISEMENT
ADVERTISEMENT

How to count unique values per groups with Pandas?

Given a DataFrame, we have to count unique values per groups.
Submitted by Pranit Sharma, on May 13, 2022

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. In this article, we are going to learn how to count unique values in a column.

Unique values are those values that only occur once.

For this purpose, we are going to use a pandas.Series.unique() method inside pandas. This method will remove all the occurrences except the first occurrence,

pandas.Series.unique() Method

This method selects the specified column passed as a parameter inside it and returns the unique values inside it.

Syntax:

Series.unique()

# or
DataFrame['col_name'].unique()

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example:

# Importing pandas package
import pandas as pd

# Create a dictionary for the dataframe
dict = {
    'Name': ['Sudhir', 'Pranit', 'Ritesh','Sanskriti', 'Rani','Megha','Suman','Ranveer'],
    'Age': [16, 27, 27, 29, 29,22,19,20],
    'Marks': [40, 24, 50, 48, 33,40,39,48]
}

# Converting Dictionary to Pandas Dataframe
df = pd.DataFrame(dict)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Selecting column Age and finding unique values
result = df['Age'].unique()

# Display result
print("Unique values in Age are:\n",result)

Output:

Example: Count unique values per groups with Pandas

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.