How to sort rows within a Pandas DataFrame?

This recipe helps you sort rows within a Pandas DataFrame

Recipe Objective

Have you ever tried to sort a dataframe according to ascending or decending order with respect to features.

So this is the recipe on we can sort rows within a Pandas DataFrame.

Step 1 - Import the library

import pandas as pd

We have imported pandas which is needed.

Step 2 - Setting up the Data

We have created a dataset by making a dictionary with features and passing it through the dataframe function. 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)

Step 3 - Sorting the dataset

For better understanding we are first sorting the dataset with respect to age and in decending order. Then again with respect to age in ascending order. Finally with respect to both first age then Comedy_Score. print(df.sort_values(by="age", ascending=0)) print(df.sort_values(by="age", ascending=1)) print(df.sort_values(by=["age", "Comedy_Score"])) 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
0    Sheldon        Copper   42             9            25
3     Howard      Wolowitz   41             8            62
1        Raj  Koothrappali   38             7            25
2    Leonard    Hofstadter   36             8            49
4        Amy        Fowler   35             5            70

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

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

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

Build a Text Generator Model using Amazon SageMaker
In this Deep Learning Project, you will train a Text Generator Model on Amazon Reviews Dataset using LSTM Algorithm in PyTorch and deploy it on Amazon SageMaker.

Natural language processing Chatbot application using NLTK for text classification
In this NLP AI application, we build the core conversational engine for a chatbot. We use the popular NLTK text classification library to achieve this.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

Learn Object Tracking (SOT, MOT) using OpenCV and Python
Get Started with Object Tracking using OpenCV and Python - Learn to implement Multiple Instance Learning Tracker (MIL) algorithm, Generic Object Tracking Using Regression Networks Tracker (GOTURN) algorithm, Kernelized Correlation Filters Tracker (KCF) algorithm, Tracking, Learning, Detection Tracker (TLD) algorithm for single and multiple object tracking from various video clips.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

Learn How to Build a Logistic Regression Model in PyTorch
In this Machine Learning Project, you will learn how to build a simple logistic regression model in PyTorch for customer churn prediction.

Skip Gram Model Python Implementation for Word Embeddings
Skip-Gram Model word2vec Example -Learn how to implement the skip gram algorithm in NLP for word embeddings on a set of documents.

Build a Multi ClassText Classification Model using Naive Bayes
Implement the Naive Bayes Algorithm to build a multi class text classification model in Python.

Build Regression (Linear,Ridge,Lasso) Models in NumPy Python
In this machine learning regression project, you will learn to build NumPy Regression Models (Linear Regression, Ridge Regression, Lasso Regression) from Scratch.

Linear Regression Model Project in Python for Beginners Part 1
Machine Learning Linear Regression Project in Python to build a simple linear regression model and master the fundamentals of regression for beginners.