Sub topic 12
Sorting by values and by index
This chapter covers sort_values and sort_index on a Series and a DataFrame. It assumes you can build a DataFrame, select with loc and iloc, and know that every row has an index label. Sorting is a short topic, but it interacts with labels, missing values, and positional selection in ways that cause bugs.
Two kinds of sorting
pandas separates sorting by what you sort on:
sort_valuesorders rows by the contents of one or more columns. On a Series it orders by the values.sort_indexorders rows (or columns) by their labels.
Both return a new object. The original is unchanged unless you pass inplace=True, which is rarely worth using because it does not save memory and blocks method chaining.
Sorting by values
The examples use the same city table as earlier chapters.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
by_pop = df.sort_values("pop_m", ascending=False)
print(by_pop)The result lists Lima, Pune, Rome, and Oslo. The index labels stay attached to their rows, so the printed index reads 1, 2, 3, 0. The labels follow the data. They are not renumbered.
For a Series, omit by:
import pandas as pd
s = pd.Series([30, 10, 20], index=["c", "a", "b"])
print(s.sort_values()) # a=10, b=20, c=30Sorting on several columns
Pass a list to by. Rows are ordered by the first column, and ties are broken by the next one. To mix directions, pass a list of booleans to ascending with one entry per column.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
out = df.sort_values(["region", "pop_m"], ascending=[True, False])
print(out["city"].tolist()) # ['Pune', 'Rome', 'Oslo', 'Lima']Regions are ordered alphabetically (AS, EU, SA). Within EU, Rome comes before Oslo because population is sorted descending.
A common error is passing ascending=False and expecting it to apply to only the first key. A single boolean applies to every key. A list whose length differs from by raises a ValueError.
Missing values
Missing values do not take part in the comparison. By default they go to the end, whether you sort ascending or descending. Use na_position="first" to move them to the front.
import pandas as pd
s = pd.Series([2.0, None, 1.0])
print(s.sort_values().tolist()) # [1.0, 2.0, nan]
print(s.sort_values(ascending=False).tolist()) # [2.0, 1.0, nan]
print(s.sort_values(na_position="first").tolist()) # [nan, 1.0, 2.0]If you expect descending order to put missing values first, the default will surprise you. Set na_position explicitly when it matters.
Ties and stability
A stable sort keeps tied rows in their original relative order. The default algorithm, quicksort, does not guarantee this. When ties exist and their order matters, pass kind="stable".
Custom ordering with `key`
The key argument is a function applied to the values before comparison. It receives a whole Series, not one element at a time, and must return a Series of the same length. The original values are what end up in the result. Only the ordering uses the transformed values.
import pandas as pd
names = pd.Series(["b", "A", "c", "B"])
print(names.sort_values().tolist())
# ['A', 'B', 'b', 'c'] (uppercase sorts before lowercase)
folded = names.sort_values(key=lambda s: s.str.lower(), kind="stable")
print(folded.tolist())
# ['A', 'b', 'B', 'c']Because the key function gets a Series, use vectorized accessors such as .str.lower(). Calling str.lower directly on the Series fails. For a DataFrame, the key is applied to each column named in by separately.
Another use of key is ordering by a custom rank. You can map labels to numbers and sort on the numbers:
import pandas as pd
sizes = pd.DataFrame({"size": ["L", "S", "M", "S"], "n": [4, 1, 2, 3]})
rank = {"S": 0, "M": 1, "L": 2}
print(sizes.sort_values("size", key=lambda s: s.map(rank)))For categories with a fixed order, an ordered category dtype is a cleaner solution, because sorting then follows the category order automatically.
Top N rows
When you only need the largest or smallest rows, nlargest and nsmallest are shorter than a sort followed by head, and they can avoid ordering the whole table.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
print(df.nlargest(2, "pop_m")["city"].tolist()) # ['Lima', 'Pune']They work on numeric and datetime columns only. They do not work on strings. The keep argument ("first", "last", or "all") controls what happens with ties at the cutoff.
Sorting by index
sort_index orders by labels instead of contents.
import pandas as pd
s = pd.Series([3, 1, 2], index=["c", "a", "b"])
print(s.sort_index()) # a=1, b=2, c=3Use axis=1 on a DataFrame to order the columns by name:
import pandas as pd
df = pd.DataFrame({"region": ["EU"], "city": ["Oslo"], "pop_m": [0.7]})
print(df.sort_index(axis=1).columns.tolist()) # ['city', 'pop_m', 'region']On a MultiIndex, level= chooses which level to sort. With sort_remaining=True, which is the default, the other levels break ties.
Why a sorted index matters
Label slicing with loc behaves differently on sorted and unsorted indexes. On a monotonic (sorted) index, the slice endpoints do not need to exist. On an unsorted index, a missing endpoint raises KeyError.
import pandas as pd
s = pd.Series([1, 2, 3], index=[10, 20, 30])
print(s.loc[15:25].tolist()) # [2]
u = pd.Series([1, 2, 3], index=[30, 10, 20])
try:
u.loc[15:25]
except KeyError as e:
print("KeyError:", e)Lookups on a sorted index can also be faster, because pandas can use binary search. If you slice by label often, sort the index once first.
Sorting and positions
Sorting changes where each row sits but not its label. After a sort, loc and iloc can return different rows for the same number:
import pandas as pd
df = pd.DataFrame({"pop_m": [0.7, 10.7, 3.1]}, index=[0, 1, 2])
ordered = df.sort_values("pop_m", ascending=False)
print(ordered.loc[0, "pop_m"]) # 0.7, label 0 is now the last row
print(ordered.iloc[0]["pop_m"]) # 10.7, position 0 is the first rowCode that relied on positional indexes and then sorts can silently pick the wrong rows. If you want a clean 0-to-N index after sorting, pass ignore_index=True or call reset_index(drop=True).
Sorting also does not break alignment. Arithmetic between two Series matches by label, so sorting one operand first does not change the result of a + b, apart from the order of the output.
Summary of options
| Argument | Applies to | Effect |
|---|---|---|
| `by` | `sort_values` on a DataFrame | Column or list of columns to sort on |
| `ascending` | both methods | One boolean, or a list matching `by` |
| `na_position` | both methods | `"last"` (default) or `"first"` |
| `kind` | single-key sorts | Use `"stable"` to preserve tie order |
| `key` | both methods | Function applied to values before comparing |
| `ignore_index` | both methods | Renumber the result `0..N-1` |
| `axis` | `sort_index` | `1` sorts columns by label |
Exercise
A DataFrame df has the index labels [0, 1, 2]. You run r = df.sort_values("score", ascending=False), and the highest score is on the row that had label 2. What do r.iloc[0] and r.loc[0] return, and how do you make r.loc[0] return the top row?
Show answer
r.iloc[0] returns the first row by position, which is the top-scoring row (label 2). r.loc[0] returns the row with label 0, wherever it now sits. To make r.loc[0] return the top row, renumber the index with df.sort_values("score", ascending=False, ignore_index=True) or r.reset_index(drop=True).