Sorting a dataframe is very often done during data processing steps. To know the best performing observation we can sort the dataset by specific column. Similarly, to know the worst performing observation, sorting can help. Sorting can help to have a cleaner look of the dataset. Python has sort_values function to sort dataframe by specific column. This article discusses step by step guide on how to sort dataframe in Python.
John has employee dataframe available with him. He is looking to perform some analysis on the same. Before starting the analysis he is looking to sort the data by first name. He is also looking forward to sort the data at multiple column level like first name, last name and gender.
Below are the key steps to follow to sort dataframe in python:
- Step 1: Import all necessary modules in Python.
import pandas as pd
- Step 2: Use sort_values function to sort Dataframe. As the requirement is to sort by only first column, we will add “first_name” in the parenthesis to sort the dataframe.
Employee_Data2=Employee_Data.sort_values(['first_name'])
- Step 3: Check output quality of the data be using the following code.
Employee_Data2.head(10)
Example 2: Sort using multiple columns
- Step 1: Use sort_values function to sort dataframe. In this example we are going to sort dataframe by 3 columns. All the necessary columns are listed in the function as mentioned below. This will sort data by 3 columns in ascending order by default. Please note if there is a need to sort dataframe in descending order, we can give option ascending=false.
Employee_Data2=Employee_Data.sort_values(['first_name','last_name','gender'])
- Step 2: Check output quality by using the below mentioned code
Employee_Data2.head(20)
Thus, John is able to sort Dataframe as per his requirement in Python.
To get top certifications in Python and build your resume visit here. Also, you can read books listed here to build strong knowledge around Python.
Visit the video tutorial as well to know the overall process:
Looking to practice more with this example? Drop us a note, we will email you the Code file:
📬 Stay Ahead in Data Science & AI – Subscribe to Newsletter!
- 🎯 Interview Series: Curated questions and answers for freshers and experienced candidates.
- 📊 Data Science for All: Simplified articles on key concepts, accessible to all levels.
- 🤖 Generative AI for All: Easy explanations on Generative AI trends transforming industries.
💡 Why Subscribe? Gain expert insights, stay ahead of trends, and prepare with confidence for your next interview.
👉 Subscribe here: