Recall & Review
beginner
What does the
loc function in pandas do?loc is used to select rows and columns by their labels (names) in a DataFrame.
Click to reveal answer
beginner
How do you select a single row with label 'A' using
loc?You use df.loc['A'] to get the row labeled 'A'.
Click to reveal answer
intermediate
How to select multiple rows labeled 'A' and 'B' and columns 'X' and 'Y' using
loc?Use df.loc[['A', 'B'], ['X', 'Y']] to select those rows and columns by label.
Click to reveal answer
intermediate
What happens if you use
loc with a label that does not exist?It raises a KeyError because the label is not found in the DataFrame index or columns.
Click to reveal answer
intermediate
Can
loc select rows using a label range like 'A' to 'C'?Yes, loc supports label slicing, so df.loc['A':'C'] selects rows from 'A' to 'C' inclusive.
Click to reveal answer
What does
df.loc['row1'] return?✗ Incorrect
loc selects rows by label, so it returns the row labeled 'row1'.
How do you select columns 'A' and 'B' for rows labeled 'x' and 'y'?
✗ Incorrect
loc uses labels, so you pass lists of row and column labels.
What error occurs if you use
loc with a missing label?✗ Incorrect
Using a label not in the index or columns raises a KeyError.
Which of these selects rows from label 'a' to 'c' inclusive?
✗ Incorrect
loc supports label slicing and includes the end label.
What does
df.loc[:, 'col1'] select?✗ Incorrect
The colon : means all rows, so this selects all rows in column 'col1'.
Explain how to use
loc to select specific rows and columns by their labels in a pandas DataFrame.Think about how you pick items by name in a list or dictionary.
You got /4 concepts.
Describe what happens if you try to select a label that does not exist using
loc.What happens when you ask for a key that is not in a dictionary?
You got /3 concepts.