0
0
Pandasdata~10 mins

melt() for unpivoting in Pandas - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to unpivot the DataFrame using pandas melt function.

Pandas
import pandas as pd

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

melted = pd.melt(df, id_vars=[1])
print(melted)
Drag options to blanks, or click blank then click option'
A['Name', 'Math']
B['Math', 'Science']
C'Math'
D'Name'
Attempts:
3 left
💡 Hint
Common Mistakes
Using columns to unpivot as id_vars instead of the identifier column.
Passing a list instead of a string for a single id_var.
2fill in blank
medium

Complete the code to specify the variable name for the unpivoted columns.

Pandas
melted = pd.melt(df, id_vars='Name', var_name=[1])
print(melted)
Drag options to blanks, or click blank then click option'
A'variable'
B'subject'
C'value'
D'Name'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the default 'variable' name without customizing.
Confusing var_name with value_name.
3fill in blank
hard

Fix the error in the code to correctly name the value column after melting.

Pandas
melted = pd.melt(df, id_vars='Name', value_name=[1])
print(melted)
Drag options to blanks, or click blank then click option'
A'score'
B'subject'
C'Name'
D'variable'
Attempts:
3 left
💡 Hint
Common Mistakes
Using value_name as the original column name.
Confusing value_name with var_name.
4fill in blank
hard

Fill both blanks to create a melted DataFrame with custom variable and value column names.

Pandas
melted = pd.melt(df, id_vars=[1], var_name=[2])
print(melted)
Drag options to blanks, or click blank then click option'
A'Name'
B'subject'
C'score'
D'Math'
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the variable and value column names.
Using a subject name as the identifier column.
5fill in blank
hard

Fill all three blanks to melt the DataFrame with custom id_vars, var_name, and value_name.

Pandas
melted = pd.melt(df, id_vars=[1], var_name=[2], value_name=[3])
print(melted)
Drag options to blanks, or click blank then click option'
A'Name'
B'score'
C'subject'
D'Math'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of parameters.
Using original column names as new variable or value names.