🎓 A1Learner
🔍
0 of 50 lessons completed

Sorting Rows

Sorting puts rows in order. sort_values sorts a DataFrame by the values in one column.

Sort by units

This frame sorts by units, smallest first. The smallest order comes first.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": [2, 1, 3],
})
print(df.sort_values("units"))

Largest first

ascending=False flips the order. The largest value comes first.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug"],
    "units": [2, 1, 3],
})
print(df.sort_values("units", ascending=False))

Sort by two columns

A list sorts by the first column, then the second. Rows that share a category order by units.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "category": ["Drink", "Drink", "Home", "Office"],
    "units": [2, 1, 3, 5],
})
print(df.sort_values(["category", "units"]))

Example

import io
import pandas as pd

SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
big = sales.sort_values("units", ascending=False)
print(big.head(5))

Key points

  • Use sort_values to order rows by one column.
  • Pass ascending=False to sort from largest to smallest.
  • Sorting by a text column orders rows from A to Z.
  • Pass a list of columns to sort by the first column, then the next.
  • sort_values returns a new DataFrame. The first frame keeps its old order.

In this example, the sales table loads from the CSV text. sort_values orders the rows by units, largest first. head(5) keeps the five largest orders. The Pen order of 5 units sits at the top.

Note

The index labels stay with their rows. The order changes, and the labels travel along.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which call sorts a DataFrame by the units column, largest first?