C. A DataFrame with rows and columns swapped, showing columns as rows.
D. A DataFrame with duplicated rows removed.
Solution
Step 1: Understand df.T usage
T is a shortcut for transpose() in pandas, swapping rows and columns.
Step 2: Visualize the transposed DataFrame
Original df has columns 'A' and 'B' with 2 rows. After transpose, columns become rows and rows become columns.
Final Answer:
A DataFrame with rows and columns swapped, showing columns as rows. -> Option C
Quick Check:
df.T = transpose DataFrame [OK]
Hint: Use df.T to quickly transpose DataFrame [OK]
Common Mistakes:
Thinking df.T sorts data
Believing df.T removes duplicates
Assuming df.T causes error
4. What is wrong with this code snippet that tries to reshape a DataFrame df using pivot()?
df.pivot(index='id', columns='variable')
medium
A. Pivot cannot be used on DataFrames with numeric columns.
B. Missing the values parameter required for pivot.
C. The index parameter should be a list, not a string.
D. The columns parameter should be omitted.
Solution
Step 1: Check pivot() required parameters
The pivot() function needs index, columns, and values to reshape data properly.
Step 2: Identify missing argument
The code misses the values argument, which tells pivot what data to fill in the new table.
Final Answer:
Missing the values parameter required for pivot. -> Option B
Quick Check:
pivot() needs values parameter [OK]
Hint: Always include values= when using pivot() [OK]
Common Mistakes:
Forgetting values parameter in pivot()
Using string instead of list for index incorrectly
Thinking pivot() can't handle numeric columns
5. You have a DataFrame df with columns ['id', 'year', 'sales_Q1', 'sales_Q2']. You want to reshape it to a long format with columns ['id', 'year', 'quarter', 'sales']. Which code correctly achieves this?
hard
A. df.stack(level=['quarter', 'sales'])
B. df.pivot(index=['id', 'year'], columns='quarter', values='sales')
C. df.transpose()
D. df.melt(id_vars=['id', 'year'], var_name='quarter', value_name='sales')
Solution
Step 1: Identify wide to long reshape method
To convert columns like 'sales_Q1', 'sales_Q2' into rows, use melt().
Step 2: Use melt() with correct parameters
Keep 'id' and 'year' fixed with id_vars, set var_name='quarter' and value_name='sales' to rename columns.
Step 3: Check other options
pivot() is for long to wide, transpose() swaps rows and columns, stack() is for multi-index reshaping but not here.
Final Answer:
df.melt(id_vars=['id', 'year'], var_name='quarter', value_name='sales') -> Option D
Quick Check:
melt() with id_vars = long format reshape [OK]
Hint: Use melt() with id_vars to reshape wide to long [OK]
Common Mistakes:
Using pivot() instead of melt() for wide to long
Trying transpose() for reshaping columns
Misusing stack() without multi-index
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.