In pandas sort_values, what does the key callable receive, and how do you use it for a case-insensitive or natural sort?
answer
- vectorized, not per cell
- same length out as in
- every by column gets it
- check the Series name
- order changes, values do not
basics
~20 sThe key callable receives each column named in by as a whole Series and must return a same-length Series of sort keys, such as s.str.lower() for case-insensitive order or extracted numbers for a natural sort.
solid answer
~40 sUnlike the key of Python's `sorted`, which is called once per element, the `key` of `sort_values` is **vectorized**: it is called once per column in `by`, receives that column as a Series, and must return a Series (or array) of the same length whose values are used only to order the rows — the returned frame shows the original values. For case-insensitive order pass `key=lambda s: s.str.lower()`; for a natural sort of codes like `'SKU-2'` and `'SKU-10'` extract the number, `key=lambda s: s.str.extract(r'(\d+)', expand=False).astype(int)`. Because the same callable runs on every column in `by`, branch on `s.name` when the keys have different types. A result of a different length raises `ValueError`. `sort_index` has a `key` too, which receives an `Index`, per level for a MultiIndex.
code
python · 16 linesimport pandas as pd
skus = pd.DataFrame({
"sku": ["SKU-10", "SKU-2", "sku-1", "SKU-21"],
"revenue": [500, 300, 300, 900],
})
print(skus.sort_values("sku")["sku"].tolist())
print(skus.sort_values("sku", key=lambda s: s.str.lower())["sku"].tolist())
natural = skus.sort_values(
["sku", "revenue"],
key=lambda s: (pd.to_numeric(s.str.extract(r"(\d+)", expand=False))
if s.name == "sku" else s),
)
print(natural["sku"].tolist())go deeper
Remember that key takes a function of a whole column, such as s.str.lower(), and only changes the order.
Explain the contract: once per by column, a Series in, a same-length Series out, and the original values in the result.
Show the working patterns: natural order by extracting numbers, branching on s.name for mixed keys, and key on sort_index for labels.
Choose between key, a helper column and an ordered categorical for shared code, based on whether the order must be visible and reused.
## What `key` is for By default `sort_values` orders text by **code point**: every uppercase letter sorts before every lowercase one, and digits inside text compare one character at a time. So `"Mixer"` lands before `"kettle Pro"`, and `"SKU-10"` lands before `"SKU-2"`. The `key` argument lets you sort by a **transformed** version of a column without changing the column itself. ## What the callable receives and must return The rules come from the `sort_values` docstring and the user guide: - `key` is called with a whole **Series** — one column from `by` — not with individual cells. It must be **vectorized**: `s.str.lower()`, not `lambda x: x.lower()`. - It is called **once per column** in `by`, each column independently. - It must return a Series (an array also works) of the **same length**. A result of a different length raises a `ValueError` saying the key function must not change the shape of the array. - The returned values are used **only to decide the order**. The result frame contains the original, untransformed values. That is the key difference from the `key` of Python's built-in `sorted`, which is called once per element; writing the per-element version here fails, because a Series has no `split` or `lower` method of its own. ## Case-insensitive order ```python products.sort_values("product", key=lambda s: s.str.lower()) ``` `s.str.lower()` maps every name to lowercase for comparison only, so `"kettle Pro"` and `"Kettle"` sort together, and the printed frame keeps the original spelling. ## Natural order for codes with numbers A product code such as `"SKU-10"` should come after `"SKU-2"`. Extract the number and sort on it: ```python skus.sort_values( "sku", key=lambda s: pd.to_numeric(s.str.extract(r"(\d+)", expand=False)), ) ``` `str.extract` with `expand=False` returns a Series holding the first captured group, and `pd.to_numeric` turns it into numbers. `astype(int)` also works when every code has a number; `pd.to_numeric` copes with a missing code, which then becomes NaN and is placed by `na_position`. ## Several columns: one callable for all of them Because `key` runs on **every** column in `by`, a text-only key breaks a mixed sort: ```python sales.sort_values(["product", "revenue"], key=lambda s: s.str.lower()) # AttributeError: Can only use .str accessor with string values ... ``` The Series passed in carries its **name**, so the callable can branch on it, as the user guide suggests: ```python sales.sort_values( ["product", "revenue"], key=lambda s: s.str.lower() if s.name == "product" else s, ) ``` ## `key` on `sort_index` `sort_index(key=...)` applies the same idea to row labels. The callable receives an **Index** and must return an Index of the same shape; for a MultiIndex it is applied **per level**, to the levels named in `level`. `df.sort_index(key=lambda idx: idx.str.lower())` gives a case-insensitive label order. ## Missing values and `Series.sort_values` The key is applied first, and the placement of missing values is decided on the **mapped** values. If the key turns a value into NaN — a code with no digits, for instance — that row is treated as missing and placed by `na_position`, `'last'` by default. `Series.sort_values` accepts the same `key` argument with the same contract, which is handy for ordering a list of product names before building a report. ## Alternatives and when to prefer them | approach | good for | |---|---| | `key=` | a one-off order that should not leave a helper column behind | | `assign` a helper column, sort, then `drop` it | an order you also want to inspect or reuse | | an ordered categorical dtype | a fixed business order such as small < medium < large | ## Common slips 1. Writing an element-wise function, such as `lambda x: int(x.split("-")[1])`, and getting `AttributeError`. 2. Forgetting that the key also runs on numeric columns in `by`. 3. Returning a filtered or deduplicated Series and hitting the shape `ValueError`. 4. Expecting the key's transformed values to appear in the result.
- Why does key=lambda x: x.lower() fail in sort_values when it works in sorted()?`sort_values` calls `key` once per column with a whole Series, not once per string. A Series has no `lower` method of its own, so the call raises `AttributeError`. Use the vectorized string accessor: `key=lambda s: s.str.lower()`.
- What does key receive in sort_index on a MultiIndex?An `Index` rather than a Series, and for a MultiIndex the callable is applied per level, to the levels named in `level`. It must return an Index of the same shape, and as in `sort_values` it only changes the order, not the labels shown.
- The key function is called once for every value, like sorted()
- key changes the values shown in the sorted DataFrame
- With several by columns, key is applied only to the first
- key may return a shorter Series to drop rows from the sort
- Default text sorting in pandas ignores case