Sorting, Ranking, and Reindexing
Data rarely arrives in the ideal order for analysis — that’s where sorting, ranking, and reindexing become essential.
Whether you need to organize data by column values or rearrange rows manually, Pandas makes it easy and intuitive.
Sorting Values
You can sort a DataFrame based on one or more columns using .sort_values().
Sort by Score
import pandas as pd
# Create a DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Score": [85, 90, 78]
}
df = pd.DataFrame(data)
# Sort by Score in descending order
df.sort_values(by="Score", ascending=False)
# Output:
# Name Score
# 1 Bob 90
# 0 Alice 85
# 2 Charlie 78
This helps you find top performers, earliest dates, or lowest prices.
Ranking Data
To rank values, use .rank(). It assigns a rank number to each value and handles ties automatically.
Rank Scores
df["Score"].rank(ascending=False)
# Output:
# 0 2.0
# 1 1.0
# 2 3.0
# Name: Score, dtype: float64
This is useful for leaderboards or percentile-based groupings.
Reindexing Rows
Reindexing lets you reset or customize the order of rows with .reindex().
Reorder Rows by Index
df.reindex([2, 0, 1])
# Output:
# Name Score
# 2 Charlie 78
# 0 Alice 85
# 1 Bob 90
Use reindexing when aligning datasets, resetting indexes, or creating customized data views.
Summary
| Feature | Method | Purpose |
|---|---|---|
| Sort Rows | sort_values() | Order rows by column values |
| Assign Rankings | rank() | Give rank numbers to values |
| Reorder Rows | reindex() | Set a custom row index order |
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.