Sorting DataFrames in pandas is a core skill for data analysts and scientists who need to organize rows by one or more columns. The sort_values and sort_index methods provide flexible control over ordering, allowing numeric, lexicographic, and custom arrangements.
Whether you are preparing a clean report or feeding machine learning pipelines, understanding how to sort pandas objects efficiently reduces errors and improves reproducibility. This guide walks through practical patterns, parameters, and common pitfalls you will encounter in real projects.
| Method | Axis | Key Parameters | Returns |
|---|---|---|---|
sort_values |
0 or 'index' | by, ascending, na_position, key | New DataFrame sorted by row labels |
sort_index |
0 or 'index' | axis, level, ascending, sort_remaining | New DataFrame sorted by column labels |
DataFrame.sort_values |
0 by default | by, axis, ascending, inplace, kind, na_position | DataFrame or None when inplace=True |
DataFrame.sort_index |
0 by default | axis, level, ascending, na_position, sort_remaining | DataFrame or Series with ordered labels |
Sort Values by Column or Columns
Using sort_values for Single and Multiple Columns
The sort_values method arranges rows based on the values in one or more columns. You pass a column name or a list of column names to the by argument, and pandas aligns rows accordingly.
When sorting by multiple columns, pandas sorts by the first column, then breaks ties using the second column, and so on. Controlling the sort direction with the ascending parameter ensures that the most important dimensions appear first in your ordered data.
Sort by Index Labels
Using sort_index for Row and Column Ordering
Use sort_index when you need to order by axis labels rather than data values. By default, it sorts row labels in ascending order, but you can also sort columns by setting axis=1.
For MultiIndex objects, the level argument lets you target a specific level for ordering. This is useful when your DataFrame has hierarchical indices and you want to arrange subsets of the data while preserving the overall structure.
Handle Missing Values and Sort Stability
Controlling Na Position and Sorting Algorithm
Missing values can disrupt expected orderings, so pandas provides the na_position parameter to manage their placement. Choose between 'first' to push NaNs to the top or 'last' to keep them at the bottom of the sorted result.
The kind parameter selects the underlying sorting algorithm, such as quicksort, mergesort, or stable. Mergesort and stable variants guarantee predictable behavior for equal keys and are recommended when the original order of tied values matters.
Best Practices for Sorting DataFrames
- Use
sort_valuesto order by data values andsort_indexto order by labels. - Specify
na_position='last'orna_position='first'to control missing value placement explicitly. - Leverage the
stablesorting algorithm when equal-key ordering must remain predictable. - Assign the result to a variable or use
inplace=Truedeliberately, remembering that in-place edits can have side effects. - Chain
reset_index(drop=True)after sorting if you want a clean integer index and no old index column.
FAQ
Reader questions
How can I sort a DataFrame so that missing values appear at the bottom while sorting by multiple columns?
Use df.sort_values(by=['col1', 'col2'], na_position='last') to sort by several columns while keeping NaN entries at the end of each group.
Can I sort in descending order without manually flipping the results?
Yes, pass ascending=False to sort_values or sort_index to reverse the sort direction for all sorted axes at once.
What happens when I try to sort a view of a DataFrame slice in pandas?
Sorting a slice may return a copy instead of modifying the original, and chained assignment can trigger a SettingWithCopyWarning . To be safe, assign the sorted result to a new variable or use df.sort_values(...).copy() .
How do I preserve the original index after sorting a DataFrame?
By default, the original index moves with the rows, so the index labels reflect the new order. If you need a fresh integer index, chain .reset_index(drop=True) after sorting.