Sort Rows or Columns in Pandas Dataframe Based on Values
Last Updated :
21 Mar, 2025
Sorting is a fundamental operation when working with data in Pandas. Whether you need to arrange rows in ascending or descending order or reorder columns based on values, Pandas provides powerful functions to make sorting easy and efficient. In this article, we'll explore different ways to sort rows and columns in a DataFrame, helping you organize and analyze your data effectively.
Sorting Rows in a DataFrame
sort_values() function sorts rows based on one or multiple columns in ascending or descending order. Functions like nsmallest() and nlargest() quickly fetch the lowest or highest values.
Example 1. Sorting Rows by a Specific Column
Python
import pandas as pd
# Creating a sample DataFrame
data = {'Name': ['Ravi', 'Anushka', 'Prajjwal', 'Kareena'],
'Age': [24, 19, 22, 25],
'Score': [85, 92, 78, 88]}
df1 = pd.DataFrame(data)
# Sorting rows based on the 'Age' column
df2 = df1.sort_values(by='Age')
print(df2)
Output Name Age Score
1 Anushka 19 92
2 Prajjwal 22 78
0 Ravi 24 85
3 Kareena 25 88
Explanation: The sort_values(by='Age') function sorts the DataFrame in ascending order based on the Age column.
Example 2. Sorting Rows in Descending Order
Python
import pandas as pd
# Creating a sample DataFrame
data = {'Name': ['Ujjwal', 'Brij', 'Kareena', 'Prajjwal'],
'Age': [24, 19, 22, 25],
'Score': [85, 92, 78, 88]}
df1 = pd.DataFrame(data)
df2 = df1.sort_values(by='Score', ascending=False)
print(df2)
Output Name Age Score
1 Brij 19 92
3 Prajjwal 25 88
0 Ujjwal 24 85
2 Kareena 22 78
Explanation: The ascending=False argument sorts the DataFrame in descending order based on the Score column.
Example 3. Sorting Rows Based on Multiple Columns
Python
import pandas as pd
# Creating a sample DataFrame
data = {'Name': ['Vaibhav', 'Brij', 'Sachin', 'Prajjwal'],
'Age': [24, 19, 22, 25],
'Score': [85, 92, 78, 88]}
df1 = pd.DataFrame(data)
df2 = df1.sort_values(by=['Age', 'Score'], ascending=[True, False])
print(df2)
Output Name Age Score
1 Brij 19 92
2 Sachin 22 78
0 Vaibhav 24 85
3 Prajjwal 25 88
Explanation: The DataFrame is first sorted by Age in ascending order. If two rows have the same Age, they are further sorted by Score in descending order.
Example 4. Sorting Rows Using nsmallest() and nlargest()
Python
import pandas as pd
# Creating a sample DataFrame
data = {'Name': ['Ujjwal', 'Brij', 'Kareena', 'Prajjwal'],
'Age': [24, 19, 22, 25],
'Score': [85, 92, 78, 88]}
df = pd.DataFrame(data)
# Getting the 2 rows with the lowest scores
res1 = df.nsmallest(2, 'Score')
print(res1)
# Getting the 2 rows with the highest scores
res2 = df.nlargest(2, 'Score')
print(res2)
Output Name Age Score
2 Kareena 22 78
0 Ujjwal 24 85
Name Age Score
1 Brij 19 92
3 Prajjwal 25 88
Explanation:
- nsmallest(n, column) returns the n rows with the smallest values in the specified column.
- nlargest(n, column) returns the n rows with the largest values in the specified column.
Sorting columns in a Dataframe
Sorting columns in Pandas helps in organizing data for better readability and analysis. The sort_index() function sorts columns alphabetically, while custom sorting can be done based on column values, such as their sum.
Example 1. Sorting Columns Alphabetically
Python
import pandas as pd
# Creating a sample DataFrame
data = {'Name': ['Anurag', 'Brij', 'Kareena', 'Prajjwal'],
'Age': [24, 19, 22, 25],
'Score': [85, 92, 78, 88]}
df1 = pd.DataFrame(data)
df2 = df1.sort_index(axis=1)
print(df2)
Output Age Name Score
0 24 Anurag 85
1 19 Brij 92
2 22 Kareena 78
3 25 Prajjwal 88
Explanation: The axis=1 argument tells Pandas to sort the column labels in alphabetical order.
Example 2: Sorting Columns by the sum of values
Python
import pandas as pd
# Creating a sample DataFrame
data = {'Name': ['Anurag', 'Aryan', 'Ravi', 'Anushka'],
'Age': [24, 19, 22, 25],
'Score': [85, 92, 78, 88]}
df1 = pd.DataFrame(data)
df2 = df.sort_index(axis=1, ascending=False)
print(df2)
Output Score Name Age
0 85 Anurag 24
1 92 Aryan 19
2 78 Ravi 22
3 88 Anushka 25
Explanation: The ascending=False argument sorts the column names in descending order.
Example 3: Sorting columns by sum of values
Python
import pandas as pd
# Sample DataFrame
data = {'A': [3, 2, 5], 'B': [1, 4, 2], 'C': [7, 6, 8]}
df1 = pd.DataFrame(data)
# Sorting columns based on sum of values
df2 = df1[sorted(df1.columns, key=lambda col: df1[col].sum())]
print(df2)
Output B A C
0 1 3 7
1 4 2 6
2 2 5 8
Explanation: This code sorts DataFrame columns in ascending order based on their sum. It retrieves column names, sorts them using sorted() with a lambda function that calculates column sums and then reorders the DataFrame accordingly.
Similar Reads
Split dataframe in Pandas based on values in multiple columns In this article, we are going to see how to divide a dataframe by various methods and based on various parameters using Python. To divide a dataframe into two or more separate dataframes based on the values present in the column we first create a data frame. Creating a DataFrame for demonestrationPy
3 min read
How to Sort a Pandas DataFrame based on column names or row index? Pandas dataframe.sort_index() method sorts objects by labels along the given axis. Basically, the sorting algorithm is applied to the axis labels rather than the actual data in the Dataframe and based on that the data is rearranged. Creating Pandas Dataframe Create a DataFrame object from the Python
3 min read
How to Select Rows from a Dataframe based on Column Values ? Selecting rows from a Pandas DataFrame based on column values is a fundamental operation in data analysis using pandas. The process allows to filter data, making it easier to perform analyses or visualizations on specific subsets. Key takeaway is that pandas provides several methods to achieve this,
4 min read
Sort the Pandas DataFrame by two or more columns In this article, our basic task is to sort the data frame based on two or more columns. For this, Dataframe.sort_values() method is used. This method sorts the data frame in Ascending or Descending order according to the columns passed inside the function. First, Let's Create a Dataframe: Python3 #i
2 min read
Split Pandas Dataframe by column value Sometimes in order to analyze the Dataframe more accurately, we need to split it into 2 or more parts. The Pandas provide the feature to split Dataframe according to column index, row index, and column values, etc. Let' see how to Split Pandas Dataframe by column value in Python? Now, let's create
3 min read