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
locslices include the end;ilocslices 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 oneloc. - 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 →
- Question 1easy
Which line selects the
product_nameandpricecolumns fromproducts? - Question 2medium
dfhas a default index 0, 1, 2, ... How many rows dodf.loc[0:3]anddf.iloc[0:3]return? - Question 3medium
productshas a default index 0–19, inproduct_idorder. 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"]) - Question 4easy
What does this print?
print(len(products.loc[products["stock"] == 0, ["product_name"]]))
- Question 5hard
Why might
products[products["stock"] == 0]["stock"] = 10leaveproductsunchanged?
Selecting columns and rows: loc and iloc
Selecting columns and rows: loc and iloc
Selecting columns and rows: loc and iloc
Selecting columns and rows: loc and iloc
Selecting columns and rows: loc and iloc
10 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.