Lesson 21 · Mastering Pandas
Mastering Data Sorting and Ranking Techniques with Pandas in Python
Sorting and ranking help us quickly organize, analyze, and understand our datasets. In this lesson, we will learn to sort by values and by index, customize…
- CourseMastering Pandas
- Lesson21 of 44
- Video18 min
- FormatJupyter notebook · 15 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbSorting and Ranking Data in Pandas#
Sorting and ranking help us quickly organize, analyze, and understand our datasets.
In this lesson, we will learn to sort by values and by index, customize order, rank data points, and work through common issues.
We will use the Titanic dataset for relatable, real-world examples.
# Suppress warnings for clarity
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# Data setup (Titanic Dataset)
import pandas as pd
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
df = pd.read_csv(url)
print(df.shape)
print(df.head(3))
What is Sorting?#
Sorting reorders rows, either by the actual data values (such as age or fare) or by the row index.
For example, we might want to see the youngest or richest Titanic passengers at the top of our list.
# Sort by a single column: Fare (ascending)
sorted_fare = df.sort_values('Fare')
print(sorted_fare[['Name', 'Fare']].head(5))
# Sort by Fare in descending order
sorted_fare_desc = df.sort_values('Fare', ascending=False)
print(sorted_fare_desc[['Name', 'Fare']].head(5))
# Sort by multiple columns: Class and Age
sorted_class_age = df.sort_values(['Pclass', 'Age'])
print(sorted_class_age[['Pclass', 'Age', 'Name']].head(7))
# Sort by index: bring rows to a predictable order
df_sorted_index = df.sort_index()
print(df_sorted_index.head(3))
How to Handle Missing Values When Sorting?#
Sorting columns with missing data (NaN) places those rows at the bottom or top, depending on the 'na_position' parameter.
# Sort with missing ages last
sorted_age = df.sort_values('Age', na_position='last')
print(sorted_age[['Name', 'Age']].tail(5))
# Sorting is not always permanent unless you set inplace=True
temp_sorted = df.sort_values('Fare')
print(df.equals(temp_sorted))
# Rank passengers by fare
df['Fare_Rank'] = df['Fare'].rank(method='min', ascending=False)
print(df[['Name', 'Fare', 'Fare_Rank']].sort_values('Fare_Rank').head(5))
# Rank with ties: average method
df['Fare_Rank_Avg'] = df['Fare'].rank(method='average', ascending=False)
print(df[['Name', 'Fare', 'Fare_Rank_Avg']].head(10))
Custom Sorting Orders#
When sorting by categories (like embarkation ports), we sometimes want a specific or logical order rather than simple alphabetical.
Pandas' 'CategoricalDtype' makes this possible.
# Sort by embarkation port (custom order)
from pandas.api.types import CategoricalDtype
embark_order = ['C', 'Q', 'S']
cat_type = CategoricalDtype(categories=embark_order, ordered=True)
df['Embarked_cat'] = df['Embarked'].astype(cat_type)
sorted_embark = df.sort_values('Embarked_cat')
print(sorted_embark[['Name', 'Embarked']].head(7))
# Ranking within groups (e.g., by sex)
df['Fare_Rank_Sex'] = df.groupby('Sex')['Fare'].rank(method='min', ascending=False)
print(df[['Name', 'Sex', 'Fare', 'Fare_Rank_Sex']].head(7))
# Use nsmallest/nlargest for quick top lists
top_5_oldest = df.nlargest(5, 'Age')
print(top_5_oldest[['Name', 'Age']])
top_5_cheapest = df.nsmallest(5, 'Fare')
print(top_5_cheapest[['Name', 'Fare']])
Troubleshooting: Common Sorting & Ranking Pitfalls#
Typical errors include spelling column names wrong, sorting objects as numbers, or missing values acting strangely.
Remember: copy your data before trying new sorts, especially with inplace=True.
# Example of sorting error: misspelled column
try:
df.sort_values('Faer')
except Exception as e:
print('Error:', e)
# Challenge: Sort by survival, then by age descending
sorted_survived_age = df.sort_values(['Survived', 'Age'], ascending=[False, False])
print(sorted_survived_age[['Name', 'Survived', 'Age']].head(5))
Recap: Powerful Sorting and Ranking with Pandas#
- Sorting organizes columns or rows quickly.
- Ranking assigns positions in a way that makes lists easy to read.
- You can handle missing data flexibly.
- Custom and grouped orders help answer advanced questions.
Use these tools oftenthey speed up almost every analysis task!
Thanks for Learning with Us!#
Sorting and ranking are at the heart of fast, insightful data analysis.
If you enjoyed this lesson, like, share, and subscribe to our channel for more hands-on pandas skill-building!
Keep practicing each technique by exploring new datasets.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



