Row order often determines whether a ranked table, grouped review, or export is easy to interpret. The pandas sort_values() method reorders complete rows from one or more DataFrame columns while keeping every value aligned with its record.
Sort keys are applied from left to right. A matching ascending list can group regions alphabetically and then rank totals from largest to smallest within each region.
Missing values sort last unless na_position=“first” is selected. Because sort_values() returns a new DataFrame by default, assigning the result preserves the source order for a direct comparison.
Related: How to create a pandas DataFrame
Related: How to filter rows in a pandas DataFrame
Steps to sort pandas DataFrame rows:
- Create the input DataFrame in sort_dataframe.py.
- sort_dataframe.py
import pandas as pd orders = pd.DataFrame( { "order_id": [1042, 1038, 1040, 1041, 1039], "region": ["West", "East", "East", "North", "West"], "total_usd": [275.0, 410.0, None, 365.0, 190.0], } ) source_order = orders["order_id"].tolist()
- Append a descending one-column sort after the DataFrame definition.
largest_first = orders.sort_values( "total_usd", ascending=False, na_position="last", )
The assigned largest_first DataFrame receives the sorted rows while orders keeps its original order.
- Append a multi-column sort after the one-column sort.
sorted_orders = orders.sort_values( ["region", "total_usd"], ascending=[True, False], na_position="last", ignore_index=True, )
Each ascending value controls the key in the same position: region sorts A to Z, then total_usd sorts largest to smallest within each region. ignore_index=True replaces the old row labels with a new integer index.
- Append fail-capable order checks and output after both sort operations.
assert largest_first["order_id"].tolist() == [1038, 1041, 1042, 1039, 1040] assert sorted_orders["order_id"].tolist() == [1038, 1040, 1041, 1042, 1039] assert orders["order_id"].tolist() == source_order print(sorted_orders.to_string(index=False)) print(f"sorted order IDs: {sorted_orders['order_id'].tolist()}") print(f"source order IDs: {orders['order_id'].tolist()}")
- Confirm the multi-key row order with the completed sorting program.
$ python3 sort_dataframe.py order_id region total_usd 1038 East 410.0 1040 East NaN 1041 North 365.0 1042 West 275.0 1039 West 190.0 sorted order IDs: [1038, 1040, 1041, 1042, 1039] source order IDs: [1042, 1038, 1040, 1041, 1039]
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.