Learn Pandas · 7/14

Sorting and Ranking Data

6 min read

Sorting and Ranking Data 🐼

Welcome! When you get a new dataset, it's often like a shuffled deck of cards—the information is all there, but it's not in a useful order. To make sense of it, you need to sort and rank it. This guide will walk you through the most common ways to bring order to your data chaos using Pandas.

Imagine you're a manager at a new online store. You have a spreadsheet with all your products, their IDs, sales numbers, and customer ratings. Right now, it's a jumble. You want to see your best-selling items, find products by their ID quickly, and see how items stack up against each other. This is where sorting and ranking come in!


1. Organizing by Index: sort_index()

The Problem: Sometimes, the row labels (the "index") of your data are out of order. For our store, maybe the Product IDs are your index, but they are all mixed up: [103, 101, 104, 102]. This makes it hard to look up a specific product.

The Solution: sort_index()

This function sorts your DataFrame based on its index labels. It’s like telling a librarian to put all the books back in order based on their catalog numbers. Suddenly, everything is easy to find. 🧘‍♀️

How It Works: sort_index() rearranges the rows of your DataFrame into ascending (A-Z, 0-9) or descending order based on the index labels.

Example:
Let's create a simple DataFrame of products with out-of-order IDs as the index.

python
import pandas as pd
import numpy as np

data = {'product_name': ['Keyboard', 'Mouse', 'Monitor', 'Webcam'],
        'sales': [150, 200, 80, 120]}
df = pd.DataFrame(data, index=[103, 101, 104, 102])

print("Original DataFrame:")
print(df)

Original DataFrame:

apache
    product_name  sales
103     Keyboard    150
101        Mouse    200
104      Monitor     80
102       Webcam    120

Now, let's sort it by the index.

python
# Sort in ascending order (the default)
sorted_df = df.sort_index()

print("\nSorted DataFrame (Ascending):")
print(sorted_df)

Sorted DataFrame (Ascending):

apache
    product_name  sales
101        Mouse    200
102       Webcam    120
103     Keyboard    150
104      Monitor     80

To sort in descending order, just add the ascending=False argument.

python
# Sort in descending order
desc_sorted_df = df.sort_index(ascending=False)

print("\nSorted DataFrame (Descending):")
print(desc_sorted_df)

Sorted DataFrame (Descending):

apache
    product_name  sales
104      Monitor     80
103     Keyboard    150
102       Webcam    120
101        Mouse    200

2. Organizing by Value: sort_values() Basics

The Problem: Looking up products by ID is great, but what about performance? You want to know which products are your best (and worst) sellers. Your data is currently not ordered by sales figures.

The Solution: sort_values()

This is one of the most-used functions in Pandas. It sorts the DataFrame based on the values in one or more columns. For our store, it's how you'd create a "Top Selling Products" list. 🛍️

How It Works: You tell sort_values() which column to look at using the by parameter, and it re-arranges the rows accordingly.

Example:
Let's use our product DataFrame and sort it by the 'sales' column.

python
data = {'product_name': ['Keyboard', 'Mouse', 'Monitor', 'Webcam'],
        'sales': [150, 200, 80, 120]}
df = pd.DataFrame(data)

# Sort by sales in descending order to see the best-sellers first
top_sellers = df.sort_values(by='sales', ascending=False)

print("Top Sellers:")
print(top_sellers)

Top Sellers:

apache
  product_name  sales
1        Mouse    200
0     Keyboard    150
3       Webcam    120
2      Monitor     80

By default, the sort is in ascending order, but for finding top performers, ascending=False is your best friend.


3. Complex Sorting: Sorting by Multiple Columns

The Problem: What happens if there's a tie? Imagine two products have the exact same number of sales. How do you decide which one to list first? You might want a secondary sorting rule, like listing them alphabetically by name.

The Solution: Pass a List to sort_values()

You can sort by multiple columns by providing a list of column names to the by parameter. Pandas will sort by the first column in the list, and then use the subsequent columns to break any ties.

How It Works: It's like sorting a music playlist. First, you sort by "Artist," but for all songs from the same artist, you then sort by "Album Year." 🎶 You can even specify a different sort order (ascending/descending) for each column.

Example:
Let's add customer ratings to our store data and sort by sales first, then by product_name.

python
data = {'product_name': ['Webcam', 'Mouse', 'Keyboard', 'Gaming Mouse'],
        'sales': [150, 200, 150, 200]}
df = pd.DataFrame(data)

# Sort by sales (desc) and then by product name (asc)
complex_sort_df = df.sort_values(by=['sales', 'product_name'], ascending=[False, True])

print("Sorted by Sales (desc), then Product Name (asc):")
print(complex_sort_df)

Sorted by Sales (desc), then Product Name (asc):

apache
   product_name  sales
3  Gaming Mouse    200
1         Mouse    200
2      Keyboard    150
0        Webcam    150

Notice how for the products with 200 sales, "Gaming Mouse" comes before "Mouse" alphabetically. The same logic applies to the products with 150 sales. The ascending=[False, True] list tells Pandas to sort the first column (sales) in descending order and the second column (product_name) in ascending order.


4. Ranking Data: The rank() Function

The Problem: Sorting tells you the order, but it doesn't assign a position like 1st, 2nd, 3rd. You don't just want a list of top sellers; you want to assign a sales rank to every product.

The Solution: rank()

The rank() function computes a numerical rank for each item in a Series. This is essential for understanding an item's standing relative to others.

How it Works (Handling Ties):
What happens if two products have the same sales? rank() gives you options via the method parameter to handle these ties. Think of it like a race where two runners finish at the same time. 🏅

  • method='average' (Default): Tied items get the average of the ranks they span. (e.g., if two items tie for 2nd and 3rd, both get a rank of 2.5).
  • method='min': Tied items get the lowest rank in their group. (e.g., two items tied for 2nd get rank 2, and the next item gets rank 4).
  • method='dense': Like 'min', but the rank always increases by 1. No gaps. (e.g., two items tied for 2nd get rank 2, and the next item gets rank 3).
  • method='first': Ranks are assigned based on the order they appear in the data. No ties are broken; the first one seen gets the lower rank.

Example:
Let's assign a sales rank to our products.

python
data = {'product_name': ['Webcam', 'Mouse', 'Keyboard', 'Gaming Mouse', 'Monitor'],
        'sales': [150, 200, 150, 200, 80]}
df = pd.DataFrame(data)

# Rank by sales, highest sales get rank 1 (ascending=False)
# Default method is 'average'
df['rank_average'] = df['sales'].rank(method='average', ascending=False)

# Using 'min' for a classic "1st, 2nd, 2nd, 4th" style ranking
df['rank_min'] = df['sales'].rank(method='min', ascending=False)

# Using 'dense' to avoid skipping ranks
df['rank_dense'] = df['sales'].rank(method='dense', ascending=False)

print(df)

Output:

apache
   product_name  sales  rank_average  rank_min  rank_dense
0        Webcam    150           3.5         3           2
1         Mouse    200           1.5         1           1
2      Keyboard    150           3.5         3           2
3  Gaming Mouse    200           1.5         1           1
4       Monitor     80           5.0         5           3

In this output, you can clearly see how each ranking method handles the two products with 200 sales and the two products with 150 sales differently. The dense rank is often preferred in business reports because it's easy for anyone to understand.


Further Reading 📚

To dive deeper, the official Pandas documentation is the best source of truth. It's detailed and has examples for every parameter.

Challenge

Challenge Instructions

You are provided with a Pandas DataFrame df containing employee sales data. Your task is to process and organize this data to gain insights into employee performance.

Complete the following steps in order:

  1. Create a new column named Total_Sales that contains the sum of the Sales_Q1 and Sales_Q2 columns for each employee.
  2. Create another new column named Dept_Rank. This column should rank employees based on their Total_Sales within their respective department. The ranking should be 'dense', meaning there are no gaps in rank numbers for ties. The employee with the highest sales in their department should receive a rank of 1.0.
  3. Reorder the entire DataFrame. First, sort by the Department column in alphabetical (ascending) order. Then, for employees within the same department, sort them by their Total_Sales in descending order.
  4. After sorting, set the Employee_ID column as the new index for the DataFrame. Finally, sort the DataFrame by this new index in ascending order to ensure it is organized by employee ID.

Expected result

The final df DataFrame should meet the following criteria:

  • It must contain two new columns: Total_Sales and Dept_Rank.
  • The Total_Sales column should accurately reflect the sum of Sales_Q1 and Sales_Q2 for each row.
  • The Dept_Rank column must contain the dense rank of each employee's total sales within their department. For example, in the 'Sales' department, the employee with the highest Total_Sales will have a Dept_Rank of 1.0, and the employee with the second-highest sales will have a rank of 2.0.
  • The DataFrame's index must be the Employee_ID values.
  • The rows of the final DataFrame must be sorted in ascending order based on the index (Employee_ID).
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.