Sort a pandas DataFrame with sort_values
Rank rows by score, sort by several columns and choose ascending or descending for each.
- sort_values(column)
- ascending=False
- Sorting by several columns
0 Ada952 Sam911 Lin88Order rows by a column
The problem
Rankings, latest orders first, alphabetical lists: sorting makes a table readable. With rows that hold several values, you need to sort by one column and keep each row's values together.
Think of it like this
Sorting a DataFrame is like re-ordering rows in a printed leaderboard by cutting the rows apart and laying them down by score. Each strip keeps its name, score and original row number.
sort_values("score", ...)✂️ Order the strips by scoreascending=False⬇️ Highest score first0, 2, 1🏷️ Each strip keeps its original row labelranked🏆 Ada, Sam, Linsort_values reorders the rows of a DataFrame by one or more columns, moving whole rows together with their index labels.
Key points
sort_values("score", ascending=False)orders the rows by score, highest first.- Whole rows move together, so each name stays with its score.
- The index labels 0, 2, 1 show where each row came from.
rankedis a new DataFrame;studentskeeps its original order.
When should you use it?
- Rankings and top-N lists.
- Chronological order of events or orders.
- Preparing data for reports and charts.
When not to use it
- Only the top few rows of a big table:
nlargest(3, "score")is faster. - Sorting by the row labels: use
sort_index().
Example code
import pandas as pd
students = pd.DataFrame({
"name": ["Ada", "Lin", "Sam"],
"score": [95, 88, 91],
})
ranked = students.sort_values("score", ascending=False)
print(ranked)
Result of running the code
name score
0 Ada 95
2 Sam 91
1 Lin 88
Code explanation
Sort_values orders rows by score. Setting ascending to false places the largest value first.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Add rows, columns, and missing values.
- Combine filtering, sorting, and groupby into a small report.
- Load a real file, inspect dtypes, and handle invalid data.
Common mistakes
Expecting the original table to change
sort_values returns a new DataFrame by default.
students.sort_values("score")
print(students) # unchanged
students = students.sort_values("score")
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges