Sub topic 5
Sorting with a key function
This chapter assumes you can already call sort_values on one or more columns and know the difference between a Series and a DataFrame. The key argument changes what pandas compares when it orders rows. It does not change what ends up in the result.
The problem a key solves
Plain sorting compares the stored values. For text, that means comparing character codes, so every uppercase letter sorts before every lowercase letter. For numbers, it means signed order, so -9 comes before 2. Often you want a different rule: ignore case, order by magnitude, or follow a business order such as small, medium, large.
You could add a helper column, sort by it, and drop it. The key argument does the same job in one call, and the helper values never appear in your data.
import pandas as pd
cities = pd.DataFrame({
"city": ["boston", "Austin", "chicago", "Denver", "atlanta"],
"population": [650, 960, 2700, 710, 500],
})
print(cities.sort_values("city"))
print(cities.sort_values("city", key=lambda s: s.str.lower()))The first call gives Austin, Denver, atlanta, boston, chicago, because uppercase letters have lower character codes. The second call gives atlanta, Austin, boston, chicago, Denver. The city names keep their original capitalisation. Only the comparison used lowercase text.
What a key function receives and returns
The rules for sort_values are strict:
- pandas calls the function once per sort column and passes it that column as a Series.
- The function must return a Series (or array-like) of the same length. A single number is an error.
- pandas sorts by the returned values, then reorders the original rows by that result.
- The returned values are discarded afterwards.
The function is applied to the whole column at once, not to one value at a time. This is why you write s.str.lower() and not str.lower(s). It is also why a lambda that treats s as a single string fails.
Common keys
Case-insensitive text
Use s.str.lower() or s.str.casefold(). The casefold method is better for text in several languages, because it handles characters such as the German ß.
Magnitude instead of sign
Python's built-in abs works on a Series, so you can pass it directly as the key.
changes = pd.DataFrame({"item": ["a", "b", "c", "d"], "delta": [-5, 3, -1, 4]})
print(changes.sort_values("delta", key=abs))The order is c (-1), b (3), d (4), a (-5). Sorting delta without a key would put -5 first.
A fixed business order
Map each label to a number that reflects the order you want.
orders = pd.DataFrame({
"size": ["L", "S", "M", "S", "L"],
"qty": [3, 9, 4, 2, 8],
})
rank_of = {"S": 0, "M": 1, "L": 2}
print(orders.sort_values("size", key=lambda s: s.map(rank_of)))Rows come out as S, S, M, L, L. Rows with equal keys, such as the two S rows, keep a consistent relative order only if you request a stable sort (see the last section).
Any label missing from the dictionary becomes NaN after map. Those rows are then treated like missing values and go to the end, or wherever na_position says. A typo in the dictionary shows up as rows that sort in the wrong place, not as an error.
An alternative is an ordered categorical column. Sorting a categorical follows the order of its categories, so no key is needed. That is the better choice if the order is used in many places. The key approach suits a one-off sort.
Numbers hidden in text
Labels such as file2 and file10 sort as text, so file10 comes before file2. Extract the number and sort by it.
files = pd.DataFrame({"name": ["file10", "file2", "file1", "file21"]})
by_number = files.sort_values(
"name",
key=lambda s: s.str.extract(r"(\d+)", expand=False).astype(int),
)
print(by_number)The result is file1, file2, file10, file21. This pattern assumes every label contains digits. If one does not, extract returns NaN and astype(int) raises an error. Use pd.to_numeric(..., errors="coerce") if some labels may lack digits, and those rows will then sort as missing values.
Keys with several columns
When you pass a list of columns, pandas calls the key function separately on each column. A function written for strings will fail on a numeric column.
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})
def lower_text_only(s):
if pd.api.types.is_numeric_dtype(s):
return s
return s.str.lower()
print(df.sort_values(["region", "units"], key=lower_text_only))The function returns numeric columns unchanged and lowercases the others. Without the check, s.str raises an AttributeError on the units column. A sort with key=lambda s: s.str.lower() over both columns would fail for the same reason.
If you need different treatment per column, check s.name inside the function:
def per_column(s):
if s.name == "region":
return s.map({"North": 0, "East": 1, "South": 2})
return s
print(df.sort_values(["region", "units"], key=per_column, ascending=[True, False]))Here the regions follow the order North, East, South instead of alphabetical order. Within each region, units run from largest to smallest. The ascending list applies to the key output, not to the original values.
Keys and missing values
Missing values are decided by the key output, not by the original column. Two consequences follow:
- If the original column has NaN and your key keeps it as NaN,
na_positionplaces those rows as usual. - If your key turns a real value into NaN (an unmapped label, a failed extraction), that row is treated as missing too.
You can use this deliberately. To push unknown labels to the bottom, build a key that maps them to NaN and keep the default na_position="last".
Keys in sort_index
sort_index also accepts key, but it receives an Index instead of a Series. The same rules apply: return an object of the same length.
by_label = pd.DataFrame(
{"value": [1, 2, 3]},
index=["b", "C", "a"],
)
print(by_label.sort_index())
print(by_label.sort_index(key=lambda idx: idx.str.lower()))The first call returns C, a, b. The second returns a, b, C. For a MultiIndex, the key is applied to each level separately, as with columns in sort_values.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `AttributeError: Can only use .str accessor with string values` | The key ran on a numeric column | Check the dtype or `s.name` inside the key |
| Error about length or "scalar" | The key returned one value or a different length | Return a Series of the same length |
| Some rows land at the end unexpectedly | The key produced NaN for them | Check unmapped labels or failed parses |
| Result looks unsorted | The key was applied per element in your head, but pandas passes the whole column | Use vectorised methods such as `.str` and `.map` |
| Original data changed | You expected the key to modify the column | It does not. Assign the key result to a column if you want to keep it |
Stability and ties
A key often creates ties. Lowercasing makes "Austin" and "austin" equal, and a size map makes every "S" equal. The default sort algorithm for a single column does not guarantee that tied rows keep their original order. If that matters, pass kind="stable":
print(orders.sort_values("size", key=lambda s: s.map(rank_of), kind="stable"))Now the two S rows keep the order they had in orders. With a multi-column sort, pandas always uses a stable method, so ties in the first column are broken by the next column.
Exercise
A DataFrame has a column tag with values ["beta", "Alpha", "gamma", "Delta"]. Write a sort_values call that orders rows alphabetically ignoring case, and say what the order of the tag values will be. Does the tag column in the result keep its original capitalisation?
Show answer
Use df.sort_values("tag", key=lambda s: s.str.lower()). The order is Alpha, beta, Delta, gamma. Yes, the tag values keep their original capitalisation, because the key output is only used to decide the order and is then discarded.
Exercise
You run df.sort_values(["region", "units"], key=lambda s: s.str.lower()) on a DataFrame where units is numeric. What happens, and how do you fix it?
Show answer
It raises an AttributeError, because pandas calls the key on each sort column and the .str accessor does not work on a numeric column. Fix it by returning numeric columns unchanged, for example with pd.api.types.is_numeric_dtype(s) inside the key, or by checking s.name.
Exercise
You sort a size column with key=lambda s: s.map({"S": 0, "M": 1, "L": 2}), but one row contains "XL". Where does that row end up with default settings, and why?
Show answer
It goes to the end. The label "XL" is not in the dictionary, so map turns it into NaN. Rows whose key is NaN are treated as missing and placed last because the default is na_position="last".