0
0
Pandasdata~20 mins

loc for label-based selection in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Loc Label Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A
   A   B
x  10  40
y  20  50
z  30  60
B
A    20
B    50
Name: y, dtype: int64
C
A    10
B    40
Name: x, dtype: int64
DKeyError: 'y'
Attempts:
2 left
💡 Hint
Remember loc selects rows by label. Here 'y' is a row label.
data_output
intermediate
2: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)
AKeyError: "['Y', 'Z'] not in index"
B
   X   Y
b  2   6
d  4   8
C
   Y   Z
b  5   9
d  7  11
D
   Y   Z
b  6  10
d  8  12
Attempts:
2 left
💡 Hint
loc uses labels for both rows and columns. Check the selected labels carefully.
🔧 Debug
advanced
2: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)
AKeyError: 's'
BIndexError: single positional indexer is out-of-bounds
CValueError: cannot index with vector containing NA / NaN values
DTypeError: unhashable type: 'list'
Attempts:
2 left
💡 Hint
Check if the label 's' exists in the DataFrame index.
🚀 Application
advanced
2: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'])
Adf.loc[['b'], 'Y'] = 100
Bdf.loc['b', ['Y']] = 100
Cdf.loc['b', 'Y'] = 100
Ddf.loc['b']['Y'] = 100
Attempts:
2 left
💡 Hint
Use loc with row and column labels directly for assignment.
🧠 Conceptual
expert
2: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?
A
   Val
b   20
c   30
d   40
B
   Val
b   20
c   30
C
   Val
c   30
d   40
DKeyError: 'b':'d'
Attempts:
2 left
💡 Hint
loc slice includes both start and end labels.