Ranking order per group in Pandas

Learn, how can we rank order per group in Python Pandas? By Pranit Sharma Last updated : September 30, 2023

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.

Problem statement

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.

How to rank order per group in pandas?

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 program 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

The output of the above program is:

Ranking order per group in Pandas

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.