Q&A library Python

How do I sort a DataFrame by one or more columns in pandas?

Python Beginner ascendingsortingsort-values

Short answer

Use sort_values with the column name, or a list of columns for a tie-break order. Control direction per column with the ascending argument, and remember it returns a new frame unless you reassign.

The short version

Use sort_values("column"). Pass a list of columns to sort by several keys, where later columns break ties in earlier ones. The ascending argument controls direction, and it accepts a list so each column can go a different way. sort_values returns a new frame, so assign the result back.

A worked example

import pandas as pd

products = pd.DataFrame({
    "product": ["pen", "mug", "pen", "cup"],
    "price": [2, 5, 3, 4],
})

print(products.sort_values("price"))
  product  price
0     pen      2
2     pen      3
3     cup      4
1     mug      5

Sorting by several columns

Give a list, and the frame is sorted by the first column, then the second within ties, and so on.

products.sort_values(["price", "product"], ascending=[False, True])

Here price sorts high to low, and where prices tie, product sorts A to Z. Matching the ascending list to the column list is what lets each key point a different way.

The mistake of forgetting to reassign

sort_values does not change the frame in place by default, so this does nothing lasting:

products.sort_values("price")   # result discarded

Either reassign, or pass inplace=True (though reassigning is generally clearer and plays better with method chaining).

products = products.sort_values("price")

Sorting by the index instead

If you have set a meaningful index, sort_index orders by that rather than a column.

products.set_index("product").sort_index()

Getting the top or bottom rows

To pick the largest or smallest few, nlargest and nsmallest are clearer and faster than sorting the whole frame and slicing.

products.nlargest(2, "price")

This returns the two dearest products directly, without ordering every row.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project