Sort a pandas DataFrame
Sorting makes rankings, chronological records, and grouped reports easier to inspect.
What is Sort a pandas DataFrame?
Sorting makes rankings, chronological records, and grouped reports easier to inspect.
Sort DataFrame rows by one or more columns with pandas.
When should you use it?
- Read, clean, and transform tabular data.
- Analyze data from CSV, Excel, APIs, or databases.
- Prepare reports, statistics, and chart data.
Example code
main.py
import pandas as pd
students = pd.DataFrame({
"name": ["Ada", "Lin", "Sam"],
"score": [95, 88, 91],
})
ranked = students.sort_values("score", ascending=False)
print(ranked)
Expected output
name score
0 Ada 95
2 Sam 91
1 Lin 88
How it works
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.