Pandas: Unpivot DataFrames with melt()

Unpivot wide-format DataFrames into long format using the Pandas pd.melt() function. Transform columns into rows, specify identifier variables, customize output column names, and prepare clean datasets for analysis.

Introduction to pd.melt() 🔝

The pd.melt() function unpivots a DataFrame from a wide format (where attributes are spread across multiple columns) into a long format (where attributes are gathered into rows). It is widely used in data cleaning and preparing inputs for machine learning models or plotting libraries.

Create wide-format sample data 🔝

Let us start with a wide-format student dataset containing names, IDs, and subject marks across separate columns.
import pandas as pd
df = pd.DataFrame({
    "NAME": ["Ravi", "Raju", "Alex"],
    "ID": [1, 2, 3],
    "MATH": [30, 40, 50],
    "ENGLISH": [20, 30, 40]
})
print(df)
assert df.shape == (3, 4)

Expected output

   NAME  ID  MATH  ENGLISH
0  Ravi   1    30       20
1  Raju   2    40       30
2  Alex   3    50       40

Basic melting with id_vars 🔝

Use id_vars to keep specific columns as identifier variables while all other remaining columns are unpivoted into rows.
melted = pd.melt(df, id_vars=["NAME", "ID"])
print(melted)
assert len(melted) == 6

Expected output

   NAME  ID variable  value
0  Ravi   1     MATH     30
1  Raju   2     MATH     40
2  Alex   3     MATH     50
3  Ravi   1  ENGLISH     20
4  Raju   2  ENGLISH     30
5  Alex   3  ENGLISH     40

Selecting specific value columns 🔝

By default, all columns not specified in id_vars are melted. You can explicitly restrict which columns to unpivot using value_vars.
specific = pd.melt(df, id_vars=["NAME"], value_vars=["MATH"])
print(specific)
assert len(specific) == 3

Expected output

   NAME variable  value
0  Ravi     MATH     30
1  Raju     MATH     40
2  Alex     MATH     50

Customizing variable and value names 🔝

Rename the default variable and value output columns using the var_name and value_name parameters.
custom = pd.melt(df, id_vars=["NAME"], value_vars=["MATH", "ENGLISH"], 
                  var_name="SUBJECT", value_name="MARKS")
print(custom)
assert "SUBJECT" in custom.columns and "MARKS" in custom.columns

Expected output

   NAME  SUBJECT  MARKS
0  Ravi     MATH     30
1  Raju     MATH     40
2  Alex     MATH     50
3  Ravi  ENGLISH     20
4  Raju  ENGLISH     30
5  Alex  ENGLISH     40

Resetting index during melt 🔝

By default, original row index labels are preserved in the melted output. Set ignore_index=True to generate a clean RangeIndex.
reset = pd.melt(df, id_vars=["NAME"], value_vars=["MATH"], ignore_index=True)
print(reset)
assert reset.index.tolist() == [0, 1, 2]

Expected output

   NAME variable  value
0  Ravi     MATH     30
1  Raju     MATH     40
2  Alex     MATH     50

Exercise: melt student marks 🔝

Melt the student DataFrame using NAME and ID as identifier variables, renaming the variable column to COURSE and the value column to SCORE, with ignore_index=True.

Exercise solution 🔝

Solution applying all parameters together.
answer = pd.melt(df, id_vars=["NAME", "ID"], value_vars=["MATH", "ENGLISH"],
                  var_name="COURSE", value_name="SCORE", ignore_index=True)
print(answer)
assert len(answer) == 6 and "COURSE" in answer.columns

Expected output

   NAME  ID   COURSE  SCORE
0  Ravi   1     MATH     30
1  Raju   2     MATH     40
2  Alex   3     MATH     50
3  Ravi  ENGLISH     20
4  Raju  ENGLISH     30
5  Alex  ENGLISH     40

Practice in Google Colab 🔝

Open in Google Colab View on GitHub

Run examples in order, inspect melted structures and try the exercise. Save a copy to keep edits.

Reference: Pandas melt() documentation.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer