Melt helps change data from wide format to long format. This makes it easier to analyze and plot data.
Melt for wide-to-long reshaping in Data Analysis Python
Introduction
Syntax
Data Analysis Python
pd.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value')
frame is your original DataFrame.
id_vars are columns to keep as identifiers (not melted).
Examples
Data Analysis Python
pd.melt(df)
Data Analysis Python
pd.melt(df, id_vars=['Name'])Data Analysis Python
pd.melt(df, id_vars=['Name'], value_vars=['Math', 'Science'], var_name='Subject', value_name='Score')
Sample Program
This code creates a small table with student names and scores in Math and Science. Then it melts the scores into a long format with columns 'Name', 'Subject', and 'Score'.
Data Analysis Python
import pandas as pd data = { 'Name': ['Alice', 'Bob'], 'Math': [85, 90], 'Science': [92, 88] } df = pd.DataFrame(data) melted = pd.melt(df, id_vars=['Name'], value_vars=['Math', 'Science'], var_name='Subject', value_name='Score') print(melted)
Important Notes
If you don't specify id_vars, all columns are melted into variable and value columns.
Melted data is useful for plotting libraries like seaborn that expect long format.
Summary
Melt changes wide data to long data by stacking columns.
Use id_vars to keep columns fixed.
Rename variable and value columns with var_name and value_name.
Practice
1. What does the
melt function do in data analysis?easy
Solution
Step 1: Understand data formats
Wide data has many columns representing variables; long data stacks these variables into fewer columns.Step 2: Role of melt function
The melt function stacks columns into rows, converting wide data to long format.Final Answer:
It converts wide data format to long data format by stacking columns. -> Option BQuick Check:
melt = wide to long [OK]
Hint: Melt stacks columns into rows to reshape wide data [OK]
Common Mistakes:
- Confusing melt with sorting or filtering
- Thinking melt merges dataframes
- Assuming melt changes row order only
2. Which of the following is the correct syntax to melt a dataframe
df keeping the column 'ID' fixed?easy
Solution
Step 1: Identify correct parameter for fixed columns
The parameter to keep columns fixed during melt isid_vars.Step 2: Check syntax correctness
Onlypd.melt(df, id_vars='ID')uses the correct parameter and function call.Final Answer:
pd.melt(df, id_vars='ID') -> Option AQuick Check:
Use id_vars to keep columns fixed [OK]
Hint: Use id_vars to keep columns fixed in melt [OK]
Common Mistakes:
- Using wrong parameter names like fixed or keep
- Calling melt as a dataframe method without pd
- Passing id instead of id_vars
3. Given the dataframe:
What is the output?
import pandas as pd
df = pd.DataFrame({
'ID': [1, 2],
'Math': [90, 80],
'Science': [85, 95]
})
result = pd.melt(df, id_vars='ID', var_name='Subject', value_name='Score')
print(result)What is the output?
medium
Solution
Step 1: Understand melt with id_vars and renaming
Keeping 'ID' fixed, melt stacks 'Math' and 'Science' into one column named 'Subject' and their values into 'Score'.Step 2: Predict output rows and columns
There are 2 rows originally and 2 subject columns, so output has 4 rows with columns 'ID', 'Subject', 'Score'.Final Answer:
A dataframe with columns ID, Subject, Score and 4 rows stacking Math and Science scores. -> Option CQuick Check:
melt stacks columns into rows with renamed columns [OK]
Hint: Melt stacks columns into rows, increasing row count [OK]
Common Mistakes:
- Expecting original wide format output
- Thinking var_name/value_name cause errors
- Ignoring increase in row count after melt
4. What is wrong with this code snippet?
import pandas as pd
df = pd.DataFrame({'ID':[1,2],'A':[10,20],'B':[30,40]})
result = pd.melt(df, id='ID', var_name='Variable', value_name='Value')
print(result)medium
Solution
Step 1: Check parameter names in melt
The correct parameter to specify fixed columns isid_vars, notid.Step 2: Identify error cause
Usingid='ID'causes a TypeError because melt does not recognize 'id'.Final Answer:
The parameter 'id' should be 'id_vars' in pd.melt. -> Option AQuick Check:
Use id_vars, not id, to fix columns [OK]
Hint: Use id_vars, not id, to keep columns fixed in melt [OK]
Common Mistakes:
- Using 'id' instead of 'id_vars'
- Thinking melt cannot rename columns
- Assuming print causes error
5. You have a dataframe:
You want to reshape it to long format with columns:
import pandas as pd
df = pd.DataFrame({
'Student': ['Alice', 'Bob'],
'Math_2023': [88, 92],
'Science_2023': [95, 85],
'Math_2024': [90, 94],
'Science_2024': [93, 89]
})You want to reshape it to long format with columns:
Student, Year, Subject, and Score. Which approach is correct?hard
Solution
Step 1: Melt keeping 'Student' fixed
Useid_vars=['Student']to keep student names fixed and stack the year-subject columns.Step 2: Split the combined variable column
The variable column contains strings like 'Math_2023'; split this into 'Subject' and 'Year' columns manually after melt.Final Answer:
Use melt with id_vars=['Student'], then split the variable column into 'Subject' and 'Year'. -> Option DQuick Check:
Melt then split combined columns for multi-level info [OK]
Hint: Melt first, then split combined variable names into parts [OK]
Common Mistakes:
- Trying to split variable names automatically in melt
- Using id_vars with non-existing columns
- Not splitting combined variable names after melt
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
