Ranking order per group in Pandas

Learn, how can we rank order per group in Python Pandas?
Submitted by Pranit Sharma, on September 15, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

How to rank order per group in pandas?

Suppose, we have a DataFrame with columns X, Y, and Z, and we need to rank each X item within each Y and then see mean rank and other stats across groups.

For this purpose, we will first use the groupby() method on the Y column with X column and then we will use the rank method and pass ascending=False as an argument.

The groupby() is a simple but very useful concept in Pandas. By using groupby(), we can create grouping of certain values and perform some operations on those values.

The groupby() method split the object, apply some operations, and then combines them to create a group hence a large amount of data and computations can be performed on these groups.

The groupby operation packs the data into an object and if we want to check out that data, we need to access that object.

Let us understand with the help of an example,

Python code to rank order per group in pandas

# Importing pandas package
import pandas as pd

# Importing sqlalchemy library
import sqlalchemy

# Setting up the connection to the database
db = sqlalchemy.create_engine('mysql://root:1234@localhost/includehelp')

# Creating dictionary
d = {
    'X':[10110,10110,10110,20401,20401,20401,20401,20401],
    'Y':[33,33,29,12,28,28,28,12],
    'Z':[1,1,1,1,1,1,1,1]
}

# Creating DataFrame
df = pd.DataFrame(d)

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

# using group by method and creating rank column
df['rank'] = df.groupby("X")["Y"].rank("dense", ascending=False)

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output:

Ranking order per group in Pandas

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




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.