D. The index list length does not match the number of rows
Solution
Step 1: Check DataFrame shape
The DataFrame has 2 rows but the new index list has 3 labels.
Step 2: Understand index assignment rules
When assigning to df.index, the length must match the number of rows exactly.
Final Answer:
The index list length does not match the number of rows -> Option D
Quick Check:
Index length must equal row count [OK]
Hint: Index length must match rows count exactly [OK]
Common Mistakes:
Assigning index list with wrong length
Thinking columns rename affects index
Assuming any list can be index regardless of length
5. You have a DataFrame df with columns ['name', 'age', 'city'] and default numeric index. How do you rename the columns to ['Name', 'Age', 'City'] and set the index to the 'name' column in one step?
hard
A. df.columns = ['Name', 'Age', 'City']; df.set_index('name', inplace=True)
B. df.rename(columns={'name':'Name', 'age':'Age', 'city':'City'}, inplace=True); df.set_index('Name', inplace=True)
C. df.columns = ['Name', 'Age', 'City']; df.index = df['Name']
D. df.rename(index={'name':'Name'}, inplace=True); df.columns = ['Name', 'Age', 'City']
Solution
Step 1: Rename columns properly
Use df.rename(columns=..., inplace=True) to rename columns safely without losing data.
Step 2: Set the index to the renamed 'Name' column
Use df.set_index('Name', inplace=True) to set the index to the 'Name' column after renaming.
Final Answer:
df.rename(columns={'name':'Name', 'age':'Age', 'city':'City'}, inplace=True); df.set_index('Name', inplace=True) -> Option B
Quick Check:
Rename columns then set index by column name [OK]
Hint: Rename columns with rename(), then set_index() by new name [OK]
Common Mistakes:
Assigning columns list directly without rename()
Setting index before renaming columns
Assigning index to a Series without set_index()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.