Challenge - 5 Problems
Loc Label Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of loc with single label selection
What is the output of the following code snippet?
Pandas
import pandas as pd df = pd.DataFrame({ 'A': [10, 20, 30], 'B': [40, 50, 60] }, index=['x', 'y', 'z']) result = df.loc['y'] print(result)
Attempts:
2 left
💡 Hint
Remember loc selects rows by label. Here 'y' is a row label.
✗ Incorrect
Using df.loc['y'] selects the row with label 'y'. It returns a Series with values from columns A and B for that row.
❓ data_output
intermediate2:00remaining
Selecting multiple rows and columns with loc
What is the output of this code?
Pandas
import pandas as pd df = pd.DataFrame({ 'X': [1, 2, 3, 4], 'Y': [5, 6, 7, 8], 'Z': [9, 10, 11, 12] }, index=['a', 'b', 'c', 'd']) result = df.loc[['b', 'd'], ['Y', 'Z']] print(result)
Attempts:
2 left
💡 Hint
loc uses labels for both rows and columns. Check the selected labels carefully.
✗ Incorrect
df.loc[['b', 'd'], ['Y', 'Z']] selects rows 'b' and 'd' and columns 'Y' and 'Z'. The values correspond to those positions.
🔧 Debug
advanced2:00remaining
Error when using loc with missing label
What error does this code raise?
Pandas
import pandas as pd df = pd.DataFrame({'A': [1, 2, 3]}, index=['p', 'q', 'r']) result = df.loc['s'] print(result)
Attempts:
2 left
💡 Hint
Check if the label 's' exists in the DataFrame index.
✗ Incorrect
Using loc with a label not in the index raises a KeyError.
🚀 Application
advanced2:00remaining
Using loc to update values in a DataFrame
Given the DataFrame below, which option correctly updates the value in row 'b' and column 'Y' to 100 using loc?
Pandas
import pandas as pd df = pd.DataFrame({ 'X': [10, 20, 30], 'Y': [40, 50, 60] }, index=['a', 'b', 'c'])
Attempts:
2 left
💡 Hint
Use loc with row and column labels directly for assignment.
✗ Incorrect
Option C correctly assigns 100 to the cell at row 'b' and column 'Y'. Option C returns a copy and does not update the original DataFrame. Options A and C assign to slices and may cause unexpected behavior.
🧠 Conceptual
expert2:00remaining
Understanding loc with slice labels
Consider this DataFrame:
import pandas as pd
df = pd.DataFrame({'Val': [10, 20, 30, 40]}, index=['a', 'b', 'c', 'd'])
result = df.loc['b':'d']
print(result)
What is the output?Attempts:
2 left
💡 Hint
loc slice includes both start and end labels.
✗ Incorrect
When slicing with loc, both the start and end labels are included in the result.