What does pandas melt() do, and when would you reshape wide data to long?

Quick Overview

Asks what pandas melt() does and when you would reshape a DataFrame from wide to long format. Tests understanding of id_vars and value_vars, tidy data for plotting and grouping, reversing the reshape with pivot, and common mistakes such as losing an identifier column.

What does pandas melt() do, and when would you reshape wide data to long?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

What does `melt()` do in pandas, and when would you reshape a DataFrame from wide to long format? ```hint Look at the headers Picture a table with one column per month. Ask what those column headers really are, and what a plot or a `groupby` would need in order to treat them as data. ``` ### What a Strong Answer Covers - What `melt()` produces from a wide table, including the shape of the output - The roles of `id_vars`, `value_vars`, `var_name` and `value_name` - Concrete situations where long format is easier to work with, and when wide format is the better choice - How to reverse the reshape - At least one common mistake, such as losing an identifier column ### Follow-up Questions - How would you turn the long table back into the original wide table, and what goes wrong if a (city, month) pair appears twice? - Your columns are named like `sales_2023` and `units_2023`. How would you reshape so that year is one column while sales and units stay separate? - What happens to the DataFrame index when you call `melt()`? - How does `melt()` relate to `stack()`?

Overview: Asks what pandas melt() does and when you would reshape a DataFrame from wide to long format. Tests understanding of id_vars and value_vars, tidy data for plotting and grouping, reversing the reshape with pivot, and common mistakes such as losing an identifier column.

General logo
General
Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

What does melt() do in pandas, and when would you reshape a DataFrame from wide to long format?

What a Strong Answer Covers Guidance

  • What melt() produces from a wide table, including the shape of the output
  • The roles of id_vars , value_vars , var_name and value_name
  • Concrete situations where long format is easier to work with, and when wide format is the better choice
  • How to reverse the reshape
  • At least one common mistake, such as losing an identifier column

Follow-up Questions Guidance

  • How would you turn the long table back into the original wide table, and what goes wrong if a (city, month) pair appears twice?
  • Your columns are named like sales_2023 and units_2023 . How would you reshape so that year is one column while sales and units stay separate?
  • What happens to the DataFrame index when you call melt() ?
  • How does melt() relate to stack() ?