BBampaa

Lessons › Python

Python lesson

Sorting

Sorted largest first, then head(3) keeps the top three. Without ascending=False, the smallest come first.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

sort_values reorders the rows by a column. ascending=False puts the biggest first:

df.sort_values("Revenue", ascending=False).head(3)

Output:

Order Day Store Product Qty Revenue
4 O105 Wed Abuja Earbuds 4 140
7 O108 Fri Lagos Earbuds 3 105
0 O101 Mon Lagos Earbuds 2 70

Key points

sort_values("Revenue")Sort rows by a column, smallest first.
ascending=FalseFlip it: largest first.
.head(3)Then keep just the top 3.

Put together: df.sort_values("Qty", ascending=False).

Practice

Try each one in your head first, then open the answer.

1. Build a line that sorts the orders by revenue, largest first.
df.sort_values("Revenue", ascending=False)
2. Build a line that sorts the orders by quantity, smallest first.
df.sort_values("Qty")
3. Show the orders sorted by quantity, largest first.
df.sort_values("Qty", ascending=False)
4. Show the 3 biggest orders by revenue.
df.sort_values("Revenue", ascending=False).head(3)
5. Show the 2 smallest orders by revenue.
df.sort_values("Revenue").head(2)

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed