Sub topic 2
Sorting by several columns, ascending and descending
This chapter assumes you can build a DataFrame, select columns, and have used sort_values on a single column. Here you will sort on several columns at once, choose the direction for each column, and avoid the mistakes that come up most often.
Why one sort key is not enough
Sorting on one column leaves ties in an arbitrary-looking order. In the sales data, two rows can share a region, and a single-key sort says nothing about how to order them. Multi-column sorting fixes this. You name a primary key, then a tie-breaker, then a tie-breaker for that, and so on.
Here is the DataFrame used throughout this chapter.
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)Passing a list of columns
Give sort_values a list in the by argument. The first column is the primary key. Rows that tie on it are ordered by the second column, and so on down the list.
print(df.sort_values(["region", "product"]))The result has the East rows first, then North, then South. Inside each region, product A comes before product B. Index labels travel with their rows, so the left-hand index will look shuffled. The original df is not changed. sort_values returns a new DataFrame.
Mixed ascending and descending order
Pass a list of booleans to ascending, with one entry per column in by. The entries line up by position.
print(df.sort_values(["region", "units"], ascending=[True, False]))This sorts region from A to Z, then sorts units from largest to smallest inside each region. The output looks like this:
region product units price
3 East A 8.0 2.5
5 East B 7.0 4.0
0 North A 10.0 2.5
2 North B NaN 4.0
4 South A 12.0 2.5
1 South B 5.0 4.0Two details are worth noting. The units column shows as floats because the missing value forces the whole column to float. The North row with missing units sits last inside its group. That is the default behaviour covered in the next chapter, and it also applies when you sort in descending order.
A single boolean applies to every column
If you pass one boolean, it applies to all columns in by.
print(df.sort_values(["region", "product"], ascending=False))This puts South before North before East, and within each region product B before A. It is a common source of confusion because the intent is often "region ascending, units descending". For that you need the list form shown above.
The order of columns matters
Swapping the columns in by changes which column is primary, and so changes the result. The two calls below use the same columns and give different row orders.
by_region = df.sort_values(["region", "units"], ascending=[True, False])
by_units = df.sort_values(["units", "region"], ascending=[False, True])
print(by_region.index.tolist())
print(by_units.index.tolist())The first call groups rows by region and ranks units inside each group. The second ranks all rows by units, and region only breaks ties between rows with equal units. In this data no two rows share a units value, so region never breaks a tie. The second sort is effectively a single-key sort on units.
| Call | Primary key | Tie-breaker | Typical use |
|---|---|---|---|
| `by=["region", "units"]` | region | units | Report grouped by region, best rows first in each block |
| `by=["units", "region"]` | units | region | Global ranking, with region only separating equal values |
A full example: three keys, three directions
You can mix as many keys as you need. Each entry in ascending belongs to the column at the same position.
result = df.sort_values(
by=["product", "units", "region"],
ascending=[True, False, True],
)
print(result)Product A rows come first. Inside product A, units run from 12 down to 8. Region would only matter if two rows had the same product and the same units. Keeping the lists on separate, aligned lines makes this kind of call easier to review.
Common errors
The two lists have different lengths
If ascending is a list, its length must equal the length of by. Otherwise pandas raises a ValueError.
try:
df.sort_values(["region", "units"], ascending=[True])
except ValueError as err:
print("ValueError:", err)The message states that the length of ascending does not match the length of by. The fix is to supply one boolean per column, or a single boolean for all of them.
A column name is misspelled or missing
A name in by that is neither a column nor an index level raises a KeyError. Check df.columns when you see one. Column names are case-sensitive, so "Region" is not "region".
Chaining single-column sorts in the wrong order
You can get a multi-key result by sorting several times, but you must sort by the least important key first. The last sort you run becomes the primary key. It also has to be a stable sort, which keeps the earlier order among ties.
chained = (
df.sort_values("units", ascending=False)
.sort_values("region", kind="stable")
)
direct = df.sort_values(["region", "units"], ascending=[True, False])
print(chained.equals(direct))This prints True. Reversing the two calls would make units the primary key, and dropping kind="stable" removes the guarantee for ties. The single call with a list is shorter and does not depend on this subtlety, so prefer it. The kind argument is also ignored when you pass several columns to one call. Multi-column sorts are always stable. Stability gets its own chapter later.
Expecting the sort to change `df`
sort_values returns a new object. Writing df.sort_values(...) on its own line and then reading df shows the old order. Assign the result, for example df = df.sort_values(...), or use it directly in a chain.
Sorting on an index level together with columns
The names in by may also be index level names, so you can combine an index level with columns. If you set region as the index, the following call still works.
indexed = df.set_index("region")
print(indexed.sort_values(["region", "units"], ascending=[True, False]))This is handy when a grouped summary has put a key into the index and you want to sort on it along with a value column. If a name exists as both a column and an index level, pandas raises an error because the name is ambiguous. Rename one of them to avoid it.
Choosing a design
- Use one
sort_valuescall with lists forbyandascending. It is explicit and always stable. - Use a single boolean only when every column goes in the same direction.
- Put the grouping-like column first (region) and the measure you want to rank second (units).
- Keep the
byandascendinglists the same length and in the same order.
Exercise
Using the sales DataFrame, write one call that orders rows by product from A to Z, then by price from highest to lowest, then by units from lowest to highest. What does the call look like, and what happens if you write ascending=[True, False] instead of a three-item list?
Show answer
Use df.sort_values(["product", "price", "units"], ascending=[True, False, True]). With ascending=[True, False] the list has two items for three columns, so pandas raises a ValueError about mismatched lengths. If you pass a single boolean instead, it applies to all three columns, so the price and units directions could not differ.
Exercise
A colleague sorts with df.sortvalues("units", ascending=False).sortvalues("region") and expects regions in order with the largest units first inside each region. Why is this result not guaranteed, and what is a safer way to write it?
Show answer
The second call uses the default sort algorithm, which does not promise to keep the earlier order of tied rows, so the units ordering inside a region may be lost. Add kind="stable" to the second call, or better, use one call: df.sort_values(["region", "units"], ascending=[True, False]).