Sub topic 2
Sorting by several columns, ascending and descending
This chapter assumes you can build a DataFrame, select columns, and call sort_values on a single column. Here you will sort on several columns at once and choose a direction for each one.
Why sort by more than one column
Sorting by one column leaves ties in no useful order. In the sales data, "North" appears twice. You may want rows grouped by region, with the best sellers first inside each region. That needs two sort keys: a primary key (region) and a tie-breaker (units).
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],
})Passing a list of columns
Give by a list. Pandas sorts by the first column, then uses the next column only to order rows that tie on the first.
print(df.sort_values(["region", "units"], ascending=[True, False])) 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.0Regions run alphabetically. Within each region, units run from largest to smallest. The missing value in the North group goes last, because na_position defaults to "last".
One flag per column
ascending accepts either a single boolean or a list of booleans. The list must have the same length as by, and each flag applies to the column in the same position.
| Call | Effect |
|---|---|
| `ascending=True` | Every column ascending (the default) |
| `ascending=False` | Every column descending |
| `ascending=[True, False]` | First column ascending, second descending |
A single boolean applies to all columns. This is a common source of mistakes:
# Both region and units are sorted descending, which is probably not what you wanted
print(df.sort_values(["region", "units"], ascending=False))If the list lengths differ, pandas raises a ValueError:
df.sort_values(["region", "units"], ascending=[True]) # ValueErrorOrder of columns matters
The order of names in by sets priority. Sorting by ["units", "region"] ranks mainly by units and uses region only to break ties between equal unit counts. Sorting by ["region", "units"] groups by region first. Write the list from most important key to least important.
Exercise
Write a call that sorts df by product from A to Z, then by units from largest to smallest within each product. In which row positions (index labels) does product "B" start and end?
Show answer
Use df.sort_values(["product", "units"], ascending=[True, False]). The A rows come first (labels 4, 0, 3 with units 12, 10, 8). The B rows follow in the order 5, 1, 2 (units 7, 5, NaN). Product B starts at label 5 and ends at label 2, because the missing value goes last.