Bird
Raised Fist0
Pandasdata~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What does the loc function in pandas primarily do?
easy
A. Deletes rows based on conditions
B. Selects data by row and column positions
C. Sorts the DataFrame by index
D. Selects data by row and column labels

Solution

  1. Step 1: Understand the purpose of loc

    loc is designed to select data using labels, not positions.
  2. Step 2: Compare with other selection methods

    Unlike iloc which uses positions, loc uses row and column labels.
  3. Final Answer:

    Selects data by row and column labels -> Option D
  4. Quick Check:

    loc = label-based selection [OK]
Hint: Remember: loc uses labels, iloc uses positions [OK]
Common Mistakes:
  • Confusing loc with iloc
  • Thinking loc sorts data
  • Assuming loc deletes data
2. Which of the following is the correct syntax to select rows with labels 'a' and 'b' and columns 'x' and 'y' using loc?
easy
A. df.loc[a,b][x,y]
B. df.loc[['a', 'b'], ['x', 'y']]
C. df.loc[a:b, x:y]
D. df.loc('a', 'b', 'x', 'y')

Solution

  1. Step 1: Identify correct loc syntax

    loc uses square brackets with row labels first, then column labels, both as lists for multiple selections.
  2. Step 2: Check each option

    df.loc[['a', 'b'], ['x', 'y']] uses correct list syntax. Options A, B, and C use wrong syntax or parentheses.
  3. Final Answer:

    df.loc[['a', 'b'], ['x', 'y']] -> Option B
  4. Quick Check:

    Use lists inside loc brackets [OK]
Hint: Use double brackets with lists for rows and columns [OK]
Common Mistakes:
  • Using parentheses instead of brackets
  • Not using lists for multiple labels
  • Mixing label slices without quotes
3. Given the DataFrame:
import pandas as pd
df = pd.DataFrame({
  'A': [10, 20, 30],
  'B': [40, 50, 60]
}, index=['x', 'y', 'z'])

What is the output of df.loc['y', 'B']?
medium
A. 50
B. [50]
C. 40
D. Error

Solution

  1. Step 1: Understand the DataFrame structure

    Rows are labeled 'x', 'y', 'z'. Columns are 'A' and 'B'. Value at row 'y' and column 'B' is 50.
  2. Step 2: Apply loc selection

    df.loc['y', 'B'] selects the single value at row 'y' and column 'B', which is 50.
  3. Final Answer:

    50 -> Option A
  4. Quick Check:

    Label 'y' and column 'B' value = 50 [OK]
Hint: Single label loc returns a scalar value [OK]
Common Mistakes:
  • Expecting a list or Series instead of scalar
  • Confusing row and column labels
  • Using iloc syntax instead
4. What is wrong with this code snippet?
df.loc['a':'c', 'x', 'y']

Assuming df has rows labeled 'a' to 'c' and columns 'x' and 'y'.
medium
A. Too many arguments inside loc brackets
B. Row slice labels are invalid
C. Column labels must be integers
D. loc cannot slice rows

Solution

  1. Step 1: Check loc argument structure

    loc expects two arguments inside one pair of brackets: rows and columns, separated by a comma.
  2. Step 2: Identify error in code

    The code has three arguments inside brackets: 'a':'c', 'x', 'y'. This is invalid syntax.
  3. Final Answer:

    Too many arguments inside loc brackets -> Option A
  4. Quick Check:

    loc needs exactly two arguments inside brackets [OK]
Hint: Use one comma inside loc brackets for rows and columns [OK]
Common Mistakes:
  • Passing multiple column labels as separate arguments
  • Using multiple commas inside loc brackets
  • Confusing loc with multiple bracket calls
5. You have a DataFrame df with index labels as dates from '2023-01-01' to '2023-01-05' and columns ['temp', 'humidity']. How would you use loc to select all rows from '2023-01-02' to '2023-01-04' and only the 'temp' column as a DataFrame?
hard
A. df.loc[['2023-01-02', '2023-01-04'], 'temp']
B. df.loc['2023-01-02':'2023-01-04', 'temp']
C. df.loc['2023-01-02':'2023-01-04', ['temp']]
D. df.loc['temp', '2023-01-02':'2023-01-04']

Solution

  1. Step 1: Understand row and column selection

    Rows are date labels; we want a slice from '2023-01-02' to '2023-01-04'. Columns are selected by label; we want only 'temp'.
  2. Step 2: Use loc with slice and list

    Row slice is a string slice, column selection needs a list for one or more columns. So use ['temp'] for columns.
  3. Final Answer:

    df.loc['2023-01-02':'2023-01-04', ['temp']] -> Option C
  4. Quick Check:

    Slice rows by labels, columns as list [OK]
Hint: Use slice for rows and list for columns in loc [OK]
Common Mistakes:
  • Using single string for multiple columns
  • Swapping rows and columns in loc
  • Using list for row slice instead of slice
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard