← Back to Pandas Course | Chapter 9: Reshaping Data | Lesson 1 of 6

melt()

melt turns wide data (many columns) into long data (one row per measurement).

In this page:

  1. melt()
Syntax
python
long_df = pd.melt(df, id_vars=["id_column"], value_vars=["column1", "column2"],
                  var_name="variable", value_name="value")

melt()

melt(id_vars, value_vars, var_name, value_name) unpivots columns into rows. id_vars stay as identifiers, while the rest become a variable column and a value column. Long format is what many plotting and grouping tools prefer.

Note: If you leave out value_vars, every non-id column is melted.

Example: melt()

python
import pandas as pd

wide = pd.DataFrame({"name": ["Ann", "Bob"], "math": [90, 80], "art": [70, 85]})
print(wide.melt(id_vars="name", var_name="subject", value_name="score"))

# Output:
#   name subject  score
# 0  Ann    math     90
# 1  Bob    math     80
# 2  Ann     art     70
# 3  Bob     art     85
Related Topics
Common Mistakes
  1. Forgetting id_vars so identifiers get melted
  2. Not naming the new columns
  3. Confusing melt with pivot
Chapter Summary
  • melt goes from wide to long
  • id_vars stay as identifiers
  • var_name and value_name label the new columns
  • Opposite of pivot
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.