Sorting and adding columns
Python · 15 questions
Short notes
Key idea
Sort rows to see the top and bottom; add columns by computing them from existing ones. Both work on whole columns at once, with no loop.
Syntax
df.sort_values("amount", ascending=False)
df.sort_values(["city", "amount"], ascending=[True, False])
df.nlargest(5, "amount")
df["total"] = df["price"] * df["qty"]
df["big"] = df["amount"] > 1000
df = df.assign(tax=df["amount"] * 0.18)
df = df.rename(columns={"amt": "amount"})
df = df.drop(columns=["notes"])
Example
df["total"] = df["price"] * df["qty"]
top = df.sort_values("total", ascending=False).head(3)
print(top[["order_id", "total"]])
Traps
sort_valuesreturns a new DataFrame; writedf = df.sort_values(...)if you want to keep it.- The index keeps the old labels after sorting. Use
reset_index(drop=True)if positions matter. - Column maths with a text column gives an error or repeats strings; check dtypes first.
ascendingtakes a list when you sort by several columns in different directions.
Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →
- Question 1easy
You run
products.sort_values("price")on its own line. What happens toproducts? - Question 2medium
Which sorts by category A to Z, then by price highest first?
- Question 3medium
27 of the 166 order lines have no discount. What does this print?
net = order_items["quantity"] * order_items["unit_price"] - order_items["discount"] print(net.isna().sum())
- Question 4easy
What does this print?
print(products.nlargest(2, "price")["price"].sum())
- Question 5hard
Store in
resulta copy ofproductswith a columnband: "Budget" for prices below 1000, "Mid" from 1000 up to but not including 3000, and "Premium" from 3000 up. Usepd.cut.The tables are ready as DataFrames with the same names. Store your answer in
result.Tables
Sorting and adding columns
Sorting and adding columns
Sorting and adding columns
Sorting and adding columns
Sorting and adding columns
10 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.