The code uses single brackets with a comma, creating a tuple key ('X', 'Y').
Step 2: Understand pandas error type
This raises KeyError because pandas looks for a column named ('X', 'Y'), which doesn't exist.
Final Answer:
KeyError -> Option B
Quick Check:
Tuple key in single brackets causes KeyError [OK]
Hint: Use list inside double brackets, not comma in single brackets [OK]
Common Mistakes:
Using comma inside single brackets for multiple columns
Expecting no error with wrong syntax
Confusing TypeError with KeyError
5. You have a DataFrame df with columns ['Name', 'Age', 'City', 'Salary']. You want to create a new DataFrame df_selected with only 'Name' and 'Salary'. Which code correctly does this and also resets the index?
hard
A. df_selected = df[['Name', 'Salary']].reset_index(drop=True)
B. df_selected = df.loc[:, ['Name', 'Salary']].reset_index()
C. df_selected = df[['Name', 'Salary']].reset_index()
D. df_selected = df[['Name', 'Salary']].reset_index(drop=False)
Solution
Step 1: Select columns 'Name' and 'Salary'
Use double brackets with list: df[['Name', 'Salary']] to select these columns.
Step 2: Reset index without adding old index as column
Use reset_index(drop=True) to reset index and drop old index column.
Step 3: Check other options
df.loc[:, ['Name', 'Salary']].reset_index() resets index but keeps old index as column. Using reset_index() without drop=True (default behavior) keeps the old index as a new column.
Final Answer:
df_selected = df[['Name', 'Salary']].reset_index(drop=True) -> Option A
Quick Check:
Select columns + reset index drop old index = df_selected = df[['Name', 'Salary']].reset_index(drop=True) [OK]
Hint: Select columns with double brackets, reset index with drop=True [OK]
Common Mistakes:
Forgetting to use double brackets for multiple columns
Not using drop=True in reset_index to avoid old index column
Using .loc without understanding index reset effect
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.