TECHNOLOGIESTieInn Technologies

Selecting columns and rows: loc and iloc

Python · 15 questions

Short notes

Key idea

loc selects by labels (index labels and column names); iloc selects by position numbers. Both take [rows, columns].

Syntax

df.loc[5, "amount"]                 # row labelled 5, column amount
df.loc[df["city"] == "Chennai", ["order_id", "amount"]]
df.loc[:, "city":"amount"]          # label slice: includes the end
df.iloc[0]                          # first row
df.iloc[0:3, 1]                     # rows 0–2, second column
df.iloc[-1]                         # last row

Example

Set a value safely:

df.loc[df["amount"] < 0, "amount"] = 0

Filtering and assigning in one loc call changes the original DataFrame.

Traps

  • loc slices include the end; iloc slices don't. loc[0:3] can give 4 rows, iloc[0:3] gives 3.
  • After sorting or filtering, labels and positions differ. loc[0] is the row labelled 0, wherever it now sits.
  • Chained indexing (df[df.x > 0]["y"] = 1) may change a copy and raise SettingWithCopyWarning. Use one loc.
  • A single label returns a Series; a list of labels returns a DataFrame.

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

    Selecting columns and rows: loc and iloc

  1. Question 1easy

    Which line selects the product_name and price columns from products?

  2. Selecting columns and rows: loc and iloc

  3. Question 2medium

    df has a default index 0, 1, 2, ... How many rows do df.loc[0:3] and df.iloc[0:3] return?

  4. Selecting columns and rows: loc and iloc

  5. Question 3medium

    products has a default index 0–19, in product_id order. Product 1 (index 0) costs 1999, and the most expensive product costs 5999. What does this print?

    s = products.sort_values("price", ascending=False)
    print(s.loc[0, "price"] + s.iloc[0]["price"])
  6. Selecting columns and rows: loc and iloc

  7. Question 4easy

    What does this print?

    print(len(products.loc[products["stock"] == 0, ["product_name"]]))
  8. Selecting columns and rows: loc and iloc

  9. Question 5hard

    Why might products[products["stock"] == 0]["stock"] = 10 leave products unchanged?

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

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