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.
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.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
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
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
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
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
NAME and ID as identifier variables, renaming the variable column to COURSE and the value column to SCORE, with ignore_index=True.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
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.