The DataFrame has columns 'A' and 'B' only; 'C' is missing.
Step 2: Understand set_index behavior
Trying to set index to a non-existent column raises a KeyError.
Final Answer:
Column 'C' does not exist, causing an error. -> Option A
Quick Check:
Missing column in set_index causes error [OK]
Hint: Check if column exists before set_index [OK]
Common Mistakes:
Assuming set_index works without error on missing columns
Thinking set_index can't be used on DataFrames
Ignoring error messages
5. You have a DataFrame df with columns 'City', 'Year', and 'Population'. You want to quickly select all rows for the city 'Paris' using indexing. Which steps correctly prepare and select the data?
hard
A. df.set_index('City', inplace=True)\ndf.loc['Paris']
B. df.set_index('Year', inplace=True)\ndf.loc['Paris']
C. df.set_index('Population', inplace=True)\ndf.loc['Paris']
D. df.loc[df['City'] == 'Paris']
Solution
Step 1: Set 'City' as the index
Setting 'City' as index allows direct row selection by city name.
Step 2: Use loc to select rows labeled 'Paris'
With 'City' as index, df.loc['Paris'] returns all rows for Paris efficiently.
Final Answer:
df.set_index('City', inplace=True)\ndf.loc['Paris'] -> Option A
Quick Check:
Index by City, then loc['Paris'] selects rows [OK]
Hint: Set index to City, then use loc['Paris'] to select [OK]
Common Mistakes:
Setting wrong column as index
Using loc with non-index column
Not setting index before loc selection
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.