Sub topic 5
Sorting with a key function
This chapter assumes you can build a DataFrame, select columns, and tell a Series from a DataFrame. You should also know sort_values from earlier chapters. Here you will sort by a transformed version of a column without changing the stored data.
Why a key function
By default, sort_values compares the values exactly as stored. Strings sort by character code, so uppercase letters come before lowercase ones. That is often not what you want. The key argument lets you describe how to compare values while leaving the column unchanged.
How key works
key takes a function. pandas calls it once per sorted column and passes it the whole column as a Series. The function must return a Series of the same length. pandas then orders the rows by the returned values but keeps the original values in the output.
Because the function receives a Series, use vectorised tools such as the .str accessor, not per-element Python logic.
import pandas as pd
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],
})
print(df.sort_values("region", key=lambda s: s.str.lower(), ignore_index=True))The lambda lowercases each region name for comparison only. The printed region column still shows North, South and East. The ignore_index=True argument renumbers the rows 0 to 5 after sorting.
A custom order
Sometimes the order you want is not alphabetical or numeric. A common case is a fixed business order, such as East, North, South. You can map each label to a position and sort by that position.
order = {"East": 0, "North": 1, "South": 2}
print(df.sort_values("region", key=lambda s: s.map(order)))Here map turns each name into a number, and the rows are sorted by those numbers. A label missing from the dictionary becomes NaN. Those rows go last unless you set na_position.
Keys with several columns
When you sort by a list of columns, pandas applies the same key function to each column separately. A function that uses .str fails on a numeric column. Write a key that checks the type, or sort in separate steps.
print(
df.sort_values(
["region", "units"],
ascending=[True, False],
key=lambda s: s.str.lower() if s.dtype == "object" else s,
)
)For numeric columns, the key returns the column unchanged. For text columns, it lowercases first. In recent pandas versions, string columns may use the string dtype instead of object. If your check misses them, test with pd.api.types.is_numeric_dtype(s) and negate it.
Common mistakes
- Passing a function that works on one value, such as
len, instead of a function that works on a Series. Uses.str.len()instead. - Expecting the transformed values to appear in the result. They never do.
- Forgetting that a key like
s.map(order)producesNaNfor unknown labels.
Exercise
Write a call that sorts df by the "product" column in descending order of the string length of the region name. Which argument carries the length logic, and why can't it be a plain len?
Show answer
Sort by "region" with df.sort_values("region", key=lambda s: s.str.len(), ascending=False). The key argument carries the logic. It receives the whole region column as a Series, so you need the vectorised s.str.len(). Plain len would return the number of rows, not a Series, and pandas would raise an error.