All sample questions / pandas
What does print(list(melted.columns)) print? pandas Reshaping, Pivot and Melt
Block 6, Reshaping, Pivot and Melt, question 14 of the pandas sample
import pandas as pd
df = pd.DataFrame({'id': [1, 2], 'a': [10, 20]})
melted = df.melt(id_vars='id')
print(list(melted.columns))
What does this print?
Show the answer and why each option is right or wrong
Answer, A. ['id', 'variable', 'value']
- A. ['id', 'variable', 'value']
- Correct. Without value_vars, melt treats every column that is not listed in id_vars as something to melt, and the output columns are always id_vars first, then variable, then value, in that fixed order.
- B. ['id', 'a', 'variable', 'value']
- Assumes the original a column stays in the frame alongside the new variable and value columns.
- C. ['variable', 'value']
- Drops the id column entirely, as if id_vars only affected which rows are kept.
- D. ['id', 'value', 'variable']
- Swaps the order of the variable and value columns.
When value_vars is omitted, melt melts every column not named in id_vars, which is the same result as listing them all explicitly. Regardless of how many columns get melted, the output always has exactly the id columns followed by variable and then value, in that order.
The answer above is what pandas 3.0.5 printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 255 pandas interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 255 pandas questions, 9 euros
Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros
Or play the free pandas sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.