skip to content

With pandas sort_values, how do you sort by several columns with a different direction for each, and what constraints apply?

level: middleimportance: must knowfreq 62%

answer

  1. two lists side by side
  2. lengths must agree
  3. one setting for missing values
  4. index level names are allowed
  5. sort_index takes level=

basics

~10 s

Pass lists to both arguments: df.sort_values(by=['revenue', 'product'], ascending=[False, True]). The ascending list must match by's length or pandas raises ValueError, and na_position is a single setting for every key.

solid answer

~40 s

Give `by` a list of keys in priority order and `ascending` a list of booleans of the **same length**: `df.sort_values(by=['revenue', 'product'], ascending=[False, True])` puts the highest revenue first and breaks ties alphabetically. A list of the wrong length raises `ValueError: Length of ascending (1) != length of by (2)`; a single bool applies to every key. `na_position` is one string, `'last'` or `'first'`, for all keys at once. Along the rows, `by` may name **index levels** as well as columns, so a frame indexed by rep can sort by rep then revenue without `reset_index`. The `kind` argument only applies to a single key. When every key is an index level, `sort_index(level=..., ascending=[...])` does the same job.

code

python · 17 lines
python
import pandas as pd

sales = pd.DataFrame({
    "rep": ["Ana", "Ben", "Ana", "Ben", "Cy"],
    "product": ["Mixer", "Kettle", "Blender", "Juicer", "Toaster"],
    "revenue": [1200, 1200, 950, 950, 400],
})

print(sales.sort_values(by=["revenue", "product"], ascending=[False, True]))

try:
    sales.sort_values(by=["revenue", "product"], ascending=[False])
except ValueError as err:
    print(err)

reps = sales.set_index("rep")
print(reps.sort_values(by=["rep", "revenue"], ascending=[True, False]))

go deeper

for a junior

Remember that by and ascending become lists of the same length, read position by position, with the primary key first.

for a middle

Explain the length ValueError, the difference between a bare bool and a one-item list, and which arguments are per key and which apply to the whole call.

for a senior

Show you can handle the awkward cases: per-key missing-value placement with a helper column, index levels in by, and sort_index with level and sort_remaining.

for a principal

Push for one explicit multi-key sort per report, with every tie-breaker named, so the order is documented in the call rather than implied by earlier steps.

## The two lists `DataFrame.sort_values` takes the sort keys in `by` and the direction in `ascending`. With several keys, both become lists that are read **position by position**: ```python board = sales.sort_values(by=["revenue", "product"], ascending=[False, True]) ``` - The **first** name in `by` is the primary key: rows are ordered by revenue, highest first. - The **second** name only decides the order among rows that tie on every key before it — here, equal revenues are listed alphabetically by product. - `ascending[i]` belongs to `by[i]`. There is no per-key keyword; the pairing is purely positional. ## What pandas checks, and what it does not pandas validates the lengths before sorting. A list for `ascending` whose length differs from `by` raises: ``` ValueError: Length of ascending (1) != length of by (2) ``` A **single boolean** is different: `ascending=False` (not in a list) applies to every key. So `ascending=[False]` with two keys is an error, while `ascending=False` sorts both keys descending. Other arguments are **one setting for the whole call**: | argument | per key? | what it does | |---|---|---| | `ascending` | yes, as a list | direction of each key | | `na_position` | no — one string | `'last'` (default) or `'first'` for every key | | `kind` | no | applied only when `by` names a single column | | `key` | no — one callable | run on each key column separately | | `ignore_index` | no | relabel the result `0 … n - 1` | Passing a list to `na_position`, such as `['first', 'last']`, raises `ValueError: invalid na_position`. When one key needs its missing values first and another needs them last, add a helper column — for example `df.assign(no_rev=df["revenue"].isna())` — and include it in `by` with its own direction. ## Index levels as keys Along the rows (`axis=0`, the default), `by` may contain **index level names** as well as column labels. A leaderboard indexed by sales rep can be ordered by rep, then by revenue within each rep, without moving the rep out of the index: ```python reps = sales.set_index("rep") reps.sort_values(by=["rep", "revenue"], ascending=[True, False]) ``` When every key is a level of the index, `sort_index` is the dedicated method: 1. `sort_index()` orders by the whole index, level by level. 2. `sort_index(level="product")` orders by that level first; `sort_remaining=True` (the default) then sorts by the other levels to break ties. 3. `sort_index(level=["rep", "product"], ascending=[True, False])` gives each named level its own direction, just like the `ascending` list of `sort_values`. `sort_index` also has `na_position`, `ignore_index` and `key`, with the same meaning as in `sort_values`. ## Direction on text and dates `ascending=False` is not only for numbers. On a text column it gives reverse alphabetical order (by code point, so uppercase and lowercase letters are not interleaved), and on a datetime column it puts the newest dates first. That makes the most common business orders one call each: - newest orders first, then the largest amount on each day: `by=["order_date", "amount"], ascending=[False, False]`; - reps alphabetically, then their best sale first: `by=["rep", "revenue"], ascending=[True, False]`. The `ascending` argument accepts a list or a tuple of booleans; what matters is that its length matches `by`. ## Results and labels The result is a new DataFrame whose rows carry their original index labels, unless `ignore_index=True`. Nothing about a multi-key sort changes that: labels travel with rows, so `.iloc[0]` is the top row and `.loc[label]` still names a record. With `axis=1`, `sort_values` reorders **columns** by the values in one or more rows instead — rare in a report, but it explains why the docstring talks about "labels" rather than "columns". ## Common slips - Passing one direction in a list (`[False]`) for two keys and getting the length `ValueError`. - Listing the keys in the wrong priority: `by=["product", "revenue"]` sorts alphabetically first and only uses revenue to break name ties. - Expecting `na_position` to accept one value per key. - Calling `reset_index()` just to sort by a level, when `by` accepts level names directly. - Running two separate `sort_values` calls and expecting the second to keep the first order among ties; that needs `kind="stable"` on the second call, or a single call with both keys.

  • What happens if you pass ascending=False rather than ascending=[False] with two keys?
    A bare boolean is broadcast to every key, so both columns sort descending and no error is raised. Only a **list** must match `by` in length; `[False]` with two keys raises `ValueError: Length of ascending (1) != length of by (2)`.
  • One key needs missing values first and another last. How do you do that with sort_values?
    `na_position` is a single string for the whole call, and a list raises `ValueError`. Add a boolean helper column such as `df['revenue'].isna()` with `assign`, put it in `by` ahead of the key it governs with its own entry in `ascending`, and drop it after sorting.
  • When would you use sort_index instead of sort_values for a multi-key sort?
    When every key is a level of the row index. `sort_index(level=[...], ascending=[...])` sorts named levels with a direction each, and `sort_remaining=True` breaks remaining ties by the other levels. When the keys mix levels and columns, `sort_values` accepts both names in `by`.

  • ascending=[False] applies descending order to every key in by
  • na_position accepts a list with one value per key
  • You must call reset_index before sorting by an index level
  • The last column in by is the primary sort key
  • A shorter ascending list is padded with True for the remaining keys