TECHNOLOGIESTieInn Technologies

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_values returns a new DataFrame; write df = 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.
  • ascending takes 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 →

Questions

Open in Code Lab5 free questions
5 questions

    Sorting and adding columns

  1. Question 1easy

    You run products.sort_values("price") on its own line. What happens to products?

  2. Sorting and adding columns

  3. Question 2medium

    Which sorts by category A to Z, then by price highest first?

  4. Sorting and adding columns

  5. 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())
  6. Sorting and adding columns

  7. Question 4easy

    What does this print?

    print(products.nlargest(2, "price")["price"].sum())
  8. Sorting and adding columns

  9. Question 5hard

    Store in result a copy of products with a column band: "Budget" for prices below 1000, "Mid" from 1000 up to but not including 3000, and "Premium" from 3000 up. Use pd.cut.

    The tables are ready as DataFrames with the same names. Store your answer in result.

    Tables

10 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.