Use df.sort_values(by="column_name") (with ascending=False for descending order, a list of column names for multi-column tie-breaking, and ignore_index=True to reset row labels cleanly) to sort a Pandas DataFrame by column values without mutating the original DataFrame.
Basic Example
import pandas as pd
df = pd.DataFrame({
"name": ["Alice", "Bob", "Charlie", "Diana"],
"department": ["Sales", "Engineering", "Sales", "Engineering"],
"salary": [72000, 95000, 88000, 95000],
})
# 1. Sort by a single column ascending (default):
sorted_asc = df.sort_values(by="salary")
print(sorted_asc)
# name department salary
# 0 Alice Sales 72000
# 2 Charlie Sales 88000
# 1 Bob Engineering 95000
# 3 Diana Engineering 95000
# 2. Sort by multiple columns with mixed directions + clean 0..N-1 index:
sorted_multi = df.sort_values(
by=["salary", "name"],
ascending=[False, True],
ignore_index=True,
)
print(sorted_multi)
# name department salary
# 0 Bob Engineering 95000
# 1 Diana Engineering 95000
# 2 Charlie Sales 88000
# 3 Alice Sales 72000
Key Details & Edge Cases
- Original index labels stay attached unless you pass
ignore_index=True:- By default (
ignore_index=False), sorting reorders rows while preserving their original index numbers (0, 2, 1, 3). Passignore_index=True(equivalent to.reset_index(drop=True)) if you intend to slice sequentially with.ilocor iterate by row position afterward.
- By default (
NaN/None/NaTvalues always sort LAST by default (na_position="last"):- Regardless of whether
ascending=Trueorascending=False, missing values (NaN) are placed at the bottom of the sorted DataFrame unless you explicitly passna_position="first".
- Regardless of whether
- Case-insensitive string sorting (
key=lambda col: col.str.lower()):- Standard lexicographical sorting places uppercase letters before lowercase (
"Zebra"before"apple"). Pass a vectorized transformation function tokey=:df.sort_values(by="name", key=lambda col: col.str.lower())
- Standard lexicographical sorting places uppercase letters before lowercase (
- Avoid
inplace=True(use assignmentdf = df.sort_values(...)instead):- The Pandas core team discourages
inplace=Truebecause it still copies data internally, prevents method chaining, and can triggerSettingWithCopyWarningwhen applied to DataFrame slices.
- The Pandas core team discourages
- Faster top-$k$ / bottom-$k$ retrieval (
df.nlargest(k, "col")/df.nsmallest(k, "col")):- When you only need the top 5 or bottom 10 rows rather than sorting an entire multi-million-row DataFrame,
df.nlargest(5, "salary")runs in $O(N)$ instead of $O(N \log N)$.
- When you only need the top 5 or bottom 10 rows rather than sorting an entire multi-million-row DataFrame,
Comparison of Pandas DataFrame Sorting Methods
| Method | Sorts By | Supports Multi-Column Mixed Order? | Preserves Relative Order of Ties? | Best Used When |
|---|---|---|---|---|
df.sort_values(by=...) (Default) |
One or more column values | Yes (ascending=[False, True]) |
Optional (kind="mergesort" or "stable") |
Sorting rows by numeric, datetime, categorical, or string column values. |
df.sort_() |
Row or column index labels (axis=0/1) |
Yes (for MultiIndex levels) |
Yes | Restoring original index order or sorting time-series DataFrames indexed by DatetimeIndex. |
df.nlargest(n, col) / df.nsmallest(n, col) |
Top/bottom $n$ values in columns | No (all specified columns share direction) | Optional (keep="first"/"last"/"all") |
Extracting top-$k$ leaderboards or outliers faster than a full sort. |
You must log in or register to comment.
