Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Melt for wide-to-long reshaping in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Melt Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this melt operation?
Given the DataFrame below, what will be the result of melting it with id_vars=['Name'] and var_name='Year'?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({
    'Name': ['Alice', 'Bob'],
    '2019': [85, 90],
    '2020': [88, 92]
})

melted = pd.melt(df, id_vars=['Name'], var_name='Year', value_name='Score')
print(melted)
A[{'Name': 'Alice', 'Year': '2019', 'Score': 85}, {'Name': 'Alice', 'Year': '2020', 'Score': 88}, {'Name': 'Bob', 'Year': '2019', 'Score': 90}, {'Name': 'Bob', 'Year': '2020', 'Score': 92}]
B[{'Name': 'Alice', 'Year': '2019', 'Score': 85}, {'Name': 'Bob', 'Year': '2019', 'Score': 90}, {'Name': 'Alice', 'Year': '2020', 'Score': 88}, {'Name': 'Bob', 'Year': '2020', 'Score': 92}]
C[{'Name': 'Alice', 'Year': '2019', 'Score': 85}, {'Name': 'Bob', 'Year': '2019', 'Score': 90}]
D[{'Name': 'Alice', 'Year': '2019', 'Score': 85}, {'Name': 'Bob', 'Year': '2020', 'Score': 92}]
Attempts:
2 left
💡 Hint
Remember that melt stacks columns vertically, keeping id_vars fixed.
❓ data_output
intermediate
1:00remaining
How many rows after melting?
If you melt a DataFrame with 3 rows and 4 value columns (excluding id_vars), how many rows will the melted DataFrame have?
A7
B12
C3
D4
Attempts:
2 left
💡 Hint
Each original row expands into one row per melted column.
🔧 Debug
advanced
1:30remaining
Identify the error in this melt code
What error will this code raise?
Data Analysis Python
import pandas as pd

df = pd.DataFrame({'A': [1,2], 'B': [3,4]})

melted = pd.melt(df, id_vars=['C'])
print(melted)
AValueError: No var_name specified
BTypeError: id_vars must be a list
CKeyError: 'C'
DNo error, prints melted DataFrame
Attempts:
2 left
💡 Hint
Check if 'C' exists as a column in df.
🚀 Application
advanced
2:00remaining
Using melt to reshape survey data
You have a DataFrame with columns: 'Respondent', 'Q1', 'Q2', 'Q3'. You want a long format with columns: 'Respondent', 'Question', 'Answer'. Which melt call achieves this?
Apd.melt(df, id_vars=['Answer'], var_name='Question', value_name='Respondent')
Bpd.melt(df, id_vars=['Respondent'], var_name='Answer', value_name='Question')
Cpd.melt(df, id_vars=['Question'], var_name='Respondent', value_name='Answer')
Dpd.melt(df, id_vars=['Respondent'], var_name='Question', value_name='Answer')
Attempts:
2 left
💡 Hint
id_vars should be the column to keep fixed, var_name the new column for old column names.
🧠 Conceptual
expert
2:30remaining
Why use melt instead of stack for wide-to-long reshaping?
Which statement best explains why melt is preferred over stack for reshaping DataFrames with multiple value columns?
AMelt allows specifying id_vars and custom column names, making it more flexible for complex reshaping.
BStack only works on Series, not DataFrames, so melt is the only option.
CStack automatically sorts data alphabetically, which can cause data loss.
DMelt is faster because it uses less memory than stack.
Attempts:
2 left
💡 Hint
Think about control over column names and identifiers.

Practice

(1/5)
1. What does the melt function do in data analysis?
easy
A. It merges two dataframes horizontally.
B. It converts wide data format to long data format by stacking columns.
C. It filters rows based on a condition.
D. It sorts data rows based on column values.

Solution

  1. Step 1: Understand data formats

    Wide data has many columns representing variables; long data stacks these variables into fewer columns.
  2. Step 2: Role of melt function

    The melt function stacks columns into rows, converting wide data to long format.
  3. Final Answer:

    It converts wide data format to long data format by stacking columns. -> Option B
  4. Quick 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
A. pd.melt(df, id_vars='ID')
B. pd.melt(df, fixed='ID')
C. df.melt(id='ID')
D. pd.melt(df, keep='ID')

Solution

  1. Step 1: Identify correct parameter for fixed columns

    The parameter to keep columns fixed during melt is id_vars.
  2. Step 2: Check syntax correctness

    Only pd.melt(df, id_vars='ID') uses the correct parameter and function call.
  3. Final Answer:

    pd.melt(df, id_vars='ID') -> Option A
  4. Quick 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:
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
A. A dataframe with columns ID, Subject but no Score column.
B. A dataframe with columns ID, Math, Science unchanged.
C. A dataframe with columns ID, Subject, Score and 4 rows stacking Math and Science scores.
D. An error because var_name and value_name are invalid parameters.

Solution

  1. 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'.
  2. 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'.
  3. Final Answer:

    A dataframe with columns ID, Subject, Score and 4 rows stacking Math and Science scores. -> Option C
  4. Quick 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
A. The parameter 'id' should be 'id_vars' in pd.melt.
B. The dataframe is missing columns to melt.
C. The melt function cannot rename columns.
D. The print statement is incorrect.

Solution

  1. Step 1: Check parameter names in melt

    The correct parameter to specify fixed columns is id_vars, not id.
  2. Step 2: Identify error cause

    Using id='ID' causes a TypeError because melt does not recognize 'id'.
  3. Final Answer:

    The parameter 'id' should be 'id_vars' in pd.melt. -> Option A
  4. Quick 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:
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
A. Use melt with var_name=['Subject', 'Year'] to split automatically.
B. Use melt with id_vars=['Student', 'Year'] directly.
C. Use melt without id_vars and rename columns to 'Year' and 'Subject'.
D. Use melt with id_vars=['Student'], then split the variable column into 'Subject' and 'Year'.

Solution

  1. Step 1: Melt keeping 'Student' fixed

    Use id_vars=['Student'] to keep student names fixed and stack the year-subject columns.
  2. 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.
  3. Final Answer:

    Use melt with id_vars=['Student'], then split the variable column into 'Subject' and 'Year'. -> Option D
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard