How to rank a Pandas DataFrame?

This recipe helps you rank a Pandas DataFrame

Recipe Objective

While working on a dataset we sometimes need to get ranks of the columns based on the values in other features, rank can be defined in many ways like based on ascending order or decending order of the values in the feature.

This python source code does the following :
1. Creates and converts data dictionary into pandas dataframe
2. Creates new columns in the dataframe
3. Ranks dataframe in ascending and descending order

So this is the recipe on how we rank a Pandas DataFrame.

Get Closer To Your Dream of Becoming a Data Scientist with 70+ Solved End-to-End ML Projects

Step 1 - Import the library

import pandas as pd

We have only imported pandas which is needed.

Step 2 - Setting up the Data

We have created a dictionary of data and passed it in pd.DataFrame to make a dataframe with columns 'first_name', 'last_name', 'age', 'Comedy_Score' and 'Rating_Score'. raw_data = {'first_name': ['Sheldon', 'Raj', 'Leonard', 'Howard', 'Amy'], 'last_name': ['Copper', 'Koothrappali', 'Hofstadter', 'Wolowitz', 'Fowler'], 'age': [42, 38, 36, 41, 35], 'Comedy_Score': [9, 7, 8, 8, 5], 'Rating_Score': [25, 25, 49, 62, 70]} df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'Comedy_Score', 'Rating_Score']) print(df)

Explore More Data Science and Machine Learning Projects for Practice. Fast-Track Your Career Transition with ProjectPro

Step 3 - Ranking the dataframe

We want to rank the dataframe on the basis of column 'age', for better understanding we will rank on ascending as well as decending order of age. But before using rank function let us first look into its parameters.

  • axis : It is bool in which 0 signifies rows and 1 signifies column and by default it is 0.
  • method : In this we have to pass the method of ranking the dataframe, it can be 'average', 'min', 'max', 'first' and 'dense'. By default it is set to average.
  • na_option : This to decide if we want to rank NaN values as NaN or we have give the higest or lowest rank to it. By default it is set to keep.
  • ascending : This is a bool feature in which we have to especify that we want the ranking as ascending or decending.

df['Hierarchy_Rank'] = df['age'].rank(ascending=True) print(df) df['Hierarchy_Rank'] = df['age'].rank(ascending=False) print(df) So the output comes as

  first_name     last_name  age  Comedy_Score  Rating_Score
0    Sheldon        Copper   42             9            25
1        Raj  Koothrappali   38             7            25
2    Leonard    Hofstadter   36             8            49
3     Howard      Wolowitz   41             8            62
4        Amy        Fowler   35             5            70

  first_name     last_name  age  Comedy_Score  Rating_Score  Hierarchy_Rank
0    Sheldon        Copper   42             9            25             5.0
1        Raj  Koothrappali   38             7            25             3.0
2    Leonard    Hofstadter   36             8            49             2.0
3     Howard      Wolowitz   41             8            62             4.0
4        Amy        Fowler   35             5            70             1.0

  first_name     last_name  age  Comedy_Score  Rating_Score  Hierarchy_Rank
0    Sheldon        Copper   42             9            25             1.0
1        Raj  Koothrappali   38             7            25             3.0
2    Leonard    Hofstadter   36             8            49             4.0
3     Howard      Wolowitz   41             8            62             2.0
4        Amy        Fowler   35             5            70             5.0

Download Materials

What Users are saying..

profile image

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

GCP MLOps Project to Deploy ARIMA Model using uWSGI Flask
Build an end-to-end MLOps Pipeline to deploy a Time Series ARIMA Model on GCP using uWSGI and Flask

LLM Project to Build and Fine Tune a Large Language Model
In this LLM project for beginners, you will learn to build a knowledge-grounded chatbot using LLM's and learn how to fine tune it.

Locality Sensitive Hashing Python Code for Look-Alike Modelling
In this deep learning project, you will find similar images (lookalikes) using deep learning and locality sensitive hashing to find customers who are most likely to click on an ad.

Recommender System Machine Learning Project for Beginners-1
Recommender System Machine Learning Project for Beginners - Learn how to design, implement and train a rule-based recommender system in Python

Build CNN Image Classification Models for Real Time Prediction
Image Classification Project to build a CNN model in Python that can classify images into social security cards, driving licenses, and other key identity information.

Hands-On Approach to Causal Inference in Machine Learning
In this Machine Learning Project, you will learn to implement various causal inference techniques in Python to determine, how effective the sprinkler is in making the grass wet.

Build a Review Classification Model using Gated Recurrent Unit
In this Machine Learning project, you will build a classification model in python to classify the reviews of an app on a scale of 1 to 5 using Gated Recurrent Unit.

NLP Project for Beginners on Text Processing and Classification
This Project Explains the Basic Text Preprocessing and How to Build a Classification Model in Python

Hands-On Approach to Regression Discontinuity Design Python
In this machine learning project, you will learn to implement Regression Discontinuity Design Example in Python to determine the effect of age on Mortality Rate in Python.

Build CI/CD Pipeline for Machine Learning Projects using Jenkins
In this project, you will learn how to create a CI/CD pipeline for a search engine application using Jenkins.