Mathew K Analytics

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…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Sorting 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))
(891, 12)
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  

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))
                                Name  Fare
271     Tornquist, Mr. William Henry   0.0
597              Johnson, Mr. Alfred   0.0
302  Johnson, Mr. William Cahoone Jr   0.0
633    Parr, Mr. William Henry Marsh   0.0
277      Parkes, Mr. Francis "Frank"   0.0
# Sort by Fare in descending order
sorted_fare_desc = df.sort_values('Fare', ascending=False)
print(sorted_fare_desc[['Name', 'Fare']].head(5))
                                   Name      Fare
258                    Ward, Miss. Anna  512.3292
737              Lesurer, Mr. Gustave J  512.3292
679  Cardeza, Mr. Thomas Drake Martinez  512.3292
88           Fortune, Miss. Mabel Helen  263.0000
27       Fortune, Mr. Charles Alexander  263.0000
# Sort by multiple columns: Class and Age
sorted_class_age = df.sort_values(['Pclass', 'Age'])
print(sorted_class_age[['Pclass', 'Age', 'Name']].head(7))
     Pclass    Age                                 Name
305       1   0.92       Allison, Master. Hudson Trevor
297       1   2.00         Allison, Miss. Helen Loraine
445       1   4.00            Dodge, Master. Washington
802       1  11.00  Carter, Master. William Thornton II
435       1  14.00            Carter, Miss. Lucile Polk
689       1  15.00    Madill, Miss. Georgette Alexandra
329       1  16.00         Hippach, Miss. Jean Gertrude
# Sort by index: bring rows to a predictable order
df_sorted_index = df.sort_index()
print(df_sorted_index.head(3))
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  

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))
                                         Name  Age
859                          Razi, Mr. Raihed  NaN
863         Sage, Miss. Dorothy Edith "Dolly"  NaN
868               van Melkebeke, Mr. Philemon  NaN
878                        Laleff, Mr. Kristo  NaN
888  Johnston, Miss. Catherine Helen "Carrie"  NaN
# Sorting is not always permanent unless you set inplace=True
temp_sorted = df.sort_values('Fare')
print(df.equals(temp_sorted))
False
# 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))
                                   Name      Fare  Fare_Rank
737              Lesurer, Mr. Gustave J  512.3292        1.0
258                    Ward, Miss. Anna  512.3292        1.0
679  Cardeza, Mr. Thomas Drake Martinez  512.3292        1.0
88           Fortune, Miss. Mabel Helen  263.0000        4.0
341      Fortune, Miss. Alice Elizabeth  263.0000        4.0
# 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))
                                                Name     Fare  Fare_Rank_Avg
0                            Braund, Mr. Owen Harris   7.2500          815.0
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  71.2833          103.0
2                             Heikkinen, Miss. Laina   7.9250          659.5
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  53.1000          144.0
4                           Allen, Mr. William Henry   8.0500          628.0
5                                   Moran, Mr. James   8.4583          599.0
6                            McCarthy, Mr. Timothy J  51.8625          157.5
7                     Palsson, Master. Gosta Leonard  21.0750          359.5
8  Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)  11.1333          526.0
9                Nasser, Mrs. Nicholas (Adele Achem)  30.0708          233.5

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))
                             Name Embarked
258              Ward, Miss. Anna        C
125  Nicola-Yarred, Master. Elias        C
354             Yousif, Mr. Wazli        C
352            Elias, Mr. Tannous        C
128             Peter, Miss. Anna        C
641          Sagesser, Mlle. Emma        C
130          Drazenoic, Mr. Jozef        C
# 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))
                                                Name     Sex     Fare  \
0                            Braund, Mr. Owen Harris    male   7.2500   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  71.2833   
2                             Heikkinen, Miss. Laina  female   7.9250   
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  53.1000   
4                           Allen, Mr. William Henry    male   8.0500   
5                                   Moran, Mr. James    male   8.4583   
6                            McCarthy, Mr. Timothy J    male  51.8625   

   Fare_Rank_Sex  
0          501.0  
1           63.0  
2          267.0  
3           81.0  
4          344.0  
5          337.0  
6           72.0  
# 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']])
                                     Name   Age
630  Barkworth, Mr. Algernon Henry Wilson  80.0
851                   Svensson, Mr. Johan  74.0
96              Goldschmidt, Mr. George B  71.0
493               Artagaveytia, Mr. Ramon  71.0
116                  Connors, Mr. Patrick  70.5
                                Name  Fare
179              Leonard, Mr. Lionel   0.0
263            Harrison, Mr. William   0.0
271     Tornquist, Mr. William Henry   0.0
277      Parkes, Mr. Francis "Frank"   0.0
302  Johnson, Mr. William Cahoone Jr   0.0

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)
    
Error: 'Faer'
# 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))
                                          Name  Survived   Age
630       Barkworth, Mr. Algernon Henry Wilson         1  80.0
275          Andrews, Miss. Kornelia Theodosia         1  63.0
483                     Turkula, Mrs. (Hedwig)         1  63.0
570                         Harris, Mr. George         1  62.0
829  Stone, Mrs. George Nelson (Martha Evelyn)         1  62.0

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.