Sorting and ranking are essential data analysis techniques in Pandas. The sort_values(), sort_index(), and rank() functions help organize data, identify top-performing records, and prepare datasets for reporting and analysis. These operations are widely used in sales dashboards, employee performance reports, financial analysis, and business intelligence. Pandas Sorting and Ranking Practice questions with solutions help to understand the concepts
1. Python Program to Sort a DataFrame by a Single Column
Problem Statement
Write a Python program to sort employees based on their salary in ascending order.
Python Solution
import pandas as pd
data = {
"Employee": ["Rahul", "Aman", "Priya"],
"Salary": [50000, 45000, 60000]
}
df = pd.DataFrame(data)
result = df.sort_values("Salary")
print(result)
Sample Output
Employee Salary
1 Aman 45000
0 Rahul 50000
2 Priya 60000
Explanation
The sort_values() function sorts rows based on the values in the Salary column.
Concepts Covered
sort_values()- Ascending Sort
- Data Sorting
2. Python Program to Sort a DataFrame in Descending Order
Problem Statement
Write a Python program to sort products based on price in descending order.
Python Solution
import pandas as pd
data = {
"Product": ["Laptop", "Mouse", "Keyboard"],
"Price": [65000, 800, 1500]
}
df = pd.DataFrame(data)
result = df.sort_values(
"Price",
ascending=False
)
print(result)
Sample Output
Product Price
0 Laptop 65000
2 Keyboard 1500
1 Mouse 800
Explanation
Setting ascending=False sorts the DataFrame from highest to lowest values.
Concepts Covered
sort_values()- Descending Sort
- Data Ordering
3. Python Program to Sort Using Multiple Columns
Problem Statement
Write a Python program to sort employees by Department and Salary.
Python Solution
import pandas as pd
data = {
"Department": [
"IT",
"HR",
"IT",
"HR"
],
"Salary": [50000, 45000, 60000, 47000]
}
df = pd.DataFrame(data)
result = df.sort_values(
["Department", "Salary"]
)
print(result)
Sample Output
Department Salary
1 HR 45000
3 HR 47000
0 IT 50000
2 IT 60000
Explanation
Passing multiple column names sorts the DataFrame first by department and then by salary.
Concepts Covered
- Multiple Column Sorting
sort_values()- Hierarchical Sorting
4. Python Program to Sort a DataFrame by Index
Problem Statement
Write a Python program to sort a DataFrame based on its index.
Python Solution
import pandas as pd
data = {
"Marks": [90, 80, 85]
}
df = pd.DataFrame(
data,
index=[2, 0, 1]
)
result = df.sort_index()
print(result)
Sample Output
Marks
0 80
1 85
2 90
Explanation
The sort_index() function sorts rows according to their index values.
Concepts Covered
sort_index()- Index Sorting
- DataFrame Index
5. Python Program to Assign Ranks to Students
Problem Statement
Write a Python program to assign ranks to students based on their marks.
Python Solution
import pandas as pd
data = {
"Student": [
"Rahul",
"Aman",
"Priya"
],
"Marks": [85, 92, 78]
}
df = pd.DataFrame(data)
df["Rank"] = df["Marks"].rank(
ascending=False
)
print(df)
Sample Output
Student Marks Rank
0 Rahul 85 2.0
1 Aman 92 1.0
2 Priya 78 3.0
Explanation
The rank() function assigns ranking based on the values in the selected column.
Concepts Covered
rank()- Student Ranking
- Data Analysis
6. Python Program to Assign Dense Ranks
Problem Statement
Write a Python program to assign dense ranks to employees based on their salary.
Python Solution
import pandas as pd
data = {
"Employee": ["Rahul", "Aman", "Priya", "Rohit"],
"Salary": [50000, 60000, 50000, 70000]
}
df = pd.DataFrame(data)
df["Rank"] = df["Salary"].rank(
method="dense",
ascending=False
)
print(df)
Sample Output
Employee Salary Rank
0 Rahul 50000 3.0
1 Aman 60000 2.0
2 Priya 50000 3.0
3 Rohit 70000 1.0
Explanation
The dense ranking method assigns the same rank to duplicate values without skipping the next rank.
Concepts Covered
rank()method="dense"- Dense Ranking
7. Python Program to Assign Average Ranks
Problem Statement
Write a Python program to assign average ranks to duplicate values.
Python Solution
import pandas as pd
data = {
"Marks": [90, 85, 90, 80]
}
df = pd.DataFrame(data)
df["Rank"] = df["Marks"].rank(
ascending=False
)
print(df)
Sample Output
Marks Rank
0 90 1.5
1 85 3.0
2 90 1.5
3 80 4.0
Explanation
By default, rank() assigns the average rank to duplicate values.
Concepts Covered
rank()- Average Ranking
- Duplicate Values
8. Python Program to Sort Strings Alphabetically
Problem Statement
Write a Python program to sort employee names alphabetically.
Python Solution
import pandas as pd
data = {
"Employee": [
"Rahul",
"Aman",
"Priya",
"Karan"
]
}
df = pd.DataFrame(data)
result = df.sort_values("Employee")
print(result)
Sample Output
Employee
1 Aman
3 Karan
2 Priya
0 Rahul
Explanation
The sort_values() function sorts string values alphabetically.
Concepts Covered
sort_values()- String Sorting
- Alphabetical Order
9. Python Program to Sort Dates
Problem Statement
Write a Python program to sort records by joining date.
Python Solution
import pandas as pd
data = {
"Employee": ["Rahul", "Aman", "Priya"],
"Joining_Date": [
"2024-03-10",
"2023-08-15",
"2024-01-20"
]
}
df = pd.DataFrame(data)
df["Joining_Date"] = pd.to_datetime(
df["Joining_Date"]
)
result = df.sort_values("Joining_Date")
print(result)
Sample Output
Employee Joining_Date
1 Aman 2023-08-15
2 Priya 2024-01-20
0 Rahul 2024-03-10
Explanation
The to_datetime() function converts text into datetime format before sorting.
Concepts Covered
to_datetime()- Date Sorting
sort_values()
10. Python Program to Display Top 3 Highest Salaries
Problem Statement
Write a Python program to display the top three highest salaries.
Python Solution
import pandas as pd
data = {
"Employee": [
"Rahul",
"Aman",
"Priya",
"Rohit",
"Sneha"
],
"Salary": [
50000,
60000,
70000,
55000,
65000
]
}
df = pd.DataFrame(data)
result = df.sort_values(
"Salary",
ascending=False
).head(3)
print(result)
Sample Output
Employee Salary
2 Priya 70000
4 Sneha 65000
1 Aman 60000
Explanation
The DataFrame is sorted in descending order, and head(3) returns the first three rows.
Concepts Covered
sort_values()head()- Top Records
11. Python Program to Display Bottom 3 Lowest Salaries
Problem Statement
Write a Python program to display the bottom three lowest salaries.
Python Solution
import pandas as pd
data = {
"Employee": [
"Rahul",
"Aman",
"Priya",
"Rohit",
"Sneha"
],
"Salary": [
50000,
60000,
70000,
55000,
65000
]
}
df = pd.DataFrame(data)
result = df.sort_values(
"Salary"
).head(3)
print(result)
Sample Output
Employee Salary
0 Rahul 50000
3 Rohit 55000
1 Aman 60000
Explanation
The DataFrame is sorted in ascending order, and head(3) returns the three lowest salary records.
Concepts Covered
sort_values()head()- Lowest Records
12. Python Program to Sort Values While Ignoring the Original Index
Problem Statement
Write a Python program to sort a DataFrame and reset the index.
Python Solution
import pandas as pd
data = {
"Employee": ["Rahul", "Aman", "Priya"],
"Salary": [50000, 45000, 60000]
}
df = pd.DataFrame(data)
result = df.sort_values(
"Salary",
ignore_index=True
)
print(result)
Sample Output
Employee Salary
0 Aman 45000
1 Rahul 50000
2 Priya 60000
Explanation
Setting ignore_index=True resets the index after sorting.
Concepts Covered
sort_values()ignore_index- Index Reset
13. Python Program to Rank Employees Within Each Department
Problem Statement
Write a Python program to assign salary ranks within each department.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "IT", "HR", "HR"],
"Employee": ["Rahul", "Priya", "Aman", "Sneha"],
"Salary": [50000, 60000, 45000, 47000]
}
df = pd.DataFrame(data)
df["Rank"] = df.groupby(
"Department"
)["Salary"].rank(
ascending=False
)
print(df)
Sample Output
Department Employee Salary Rank
0 IT Rahul 50000 2.0
1 IT Priya 60000 1.0
2 HR Aman 45000 2.0
3 HR Sneha 47000 1.0
Explanation
The groupby() function creates separate groups, and rank() assigns rankings within each department.
Concepts Covered
groupby()rank()- Department-wise Ranking
14. Python Program to Sort Columns Alphabetically
Problem Statement
Write a Python program to sort DataFrame columns alphabetically.
Python Solution
import pandas as pd
data = {
"Salary": [50000, 60000],
"Employee": ["Rahul", "Aman"],
"Department": ["IT", "HR"]
}
df = pd.DataFrame(data)
result = df.sort_index(axis=1)
print(result)
Sample Output
Department Employee Salary
0 IT Rahul 50000
1 HR Aman 60000
Explanation
Using sort_index(axis=1) sorts the column names alphabetically.
Concepts Covered
sort_index()axis=1- Column Sorting
15. Python Program to Rank Products Based on Sales
Problem Statement
Write a Python program to rank products according to their sales.
Python Solution
import pandas as pd
data = {
"Product": [
"Laptop",
"Mouse",
"Keyboard",
"Monitor"
],
"Sales": [
250,
520,
310,
180
]
}
df = pd.DataFrame(data)
df["Rank"] = df["Sales"].rank(
ascending=False,
method="dense"
)
print(df)
Sample Output
Product Sales Rank
0 Laptop 250 3.0
1 Mouse 520 1.0
2 Keyboard 310 2.0
3 Monitor 180 4.0
Explanation
The rank() function assigns rankings based on sales values, with the highest sales receiving Rank 1.
Concepts Covered
rank()method="dense"- Product Ranking
Chapter Summary
In this chapter, you learned how to organize and analyze data using Pandas sorting and ranking functions. You practiced sorting data by values, indexes, strings, dates, and multiple columns. You also learned how to assign ranks, use dense ranking, rank data within groups, reset indexes after sorting, and identify the highest and lowest records. These techniques are commonly used in reporting, dashboards, business intelligence, HR analytics, finance, and sales analysis.
Key Takeaways
sort_values()sorts rows based on column values.sort_index()sorts rows or columns by index.ascending=Falseperforms descending sorting.ignore_index=Trueresets the index after sorting.rank()assigns rankings to numerical values.method="dense"creates continuous rankings.- Rankings can be calculated within groups using
groupby(). - Sorting can be performed on numbers, strings, dates, and multiple columns.
head()is useful for displaying top records.- Sorting and ranking are essential for data analysis and reporting.
Frequently Asked Questions (FAQs)
1. Which function is used to sort rows in Pandas?
df.sort_values("Salary")
2. How do you sort data in descending order?
df.sort_values("Salary", ascending=False)
3. Which function sorts a DataFrame by index?
df.sort_index()
4. How do you assign rankings in Pandas?
df["Rank"] = df["Marks"].rank()
5. What is the purpose of method="dense" in rank()?
It assigns consecutive ranks without skipping numbers when duplicate values exist.
6. How do you rank data within each group?
df.groupby("Department")["Salary"].rank()
7. How do you reset the index after sorting?
df.sort_values(
"Salary",
ignore_index=True
)
8. Why are sorting and ranking important in Pandas?
Sorting and ranking help organize datasets, identify top and bottom performers, generate reports, prepare dashboards, analyze trends, and simplify decision-making in data analysis and business intelligence.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
