What if you could reshape messy tables in one line instead of hours of copying?
Why melt() for unpivoting in Pandas? - Purpose & Use Cases
Imagine you have a table with sales data for different products across several months, all in separate columns. You want to analyze sales trends over time, but the data is wide and hard to compare.
Manually copying and rearranging columns into rows is slow and boring. It's easy to make mistakes, like mixing up months or missing data. Plus, if the data updates, you have to redo everything.
The melt() function quickly turns wide tables into long tables by stacking columns into rows. This makes data tidy and ready for analysis without manual copying or errors.
new_data = [] for month in ['Jan', 'Feb', 'Mar']: for i, row in df.iterrows(): new_data.append({'Product': row['Product'], 'Month': month, 'Sales': row[month]}) new_df = pd.DataFrame(new_data)
new_df = df.melt(id_vars=['Product'], var_name='Month', value_name='Sales')
It lets you quickly reshape data to explore trends, create charts, and build models with tidy, easy-to-use tables.
A store manager can transform monthly sales columns into a single 'Month' column to easily plot sales over time and spot which months perform best.
Manual reshaping is slow and error-prone.
melt() automates turning columns into rows.
This makes data tidy and ready for analysis.
Practice
pandas.melt() function primarily do to a DataFrame?Solution
Step 1: Understand the purpose of melt()
The melt() function is used to convert wide data (many columns) into long data (fewer columns, more rows).Step 2: Identify the transformation type
This process is called unpivoting, where columns become rows.Final Answer:
Transforms wide format data into long format data by unpivoting columns. -> Option CQuick Check:
melt() = unpivot wide to long [OK]
- Confusing melt() with sorting or filtering functions
- Thinking melt() aggregates data
- Assuming melt() changes row order only
df using melt() while keeping column 'ID' fixed?Solution
Step 1: Identify correct parameter usage
id_vars are columns to keep fixed; value_vars are columns to unpivot. Here, 'ID' is fixed, 'A' and 'B' are unpivoted.Step 2: Match syntax with parameters
pd.melt(df, id_vars=['ID'], value_vars=['A', 'B']) correctly uses pd.melt(df, id_vars=['ID'], value_vars=['A', 'B']). Other options swap or misuse parameters.Final Answer:
pd.melt(df, id_vars=['ID'], value_vars=['A', 'B']) -> Option AQuick Check:
id_vars = fixed columns, value_vars = columns to unpivot [OK]
- Swapping id_vars and value_vars
- Using DataFrame method without pd prefix incorrectly
- Passing wrong columns to parameters
df below:ID Jan Feb 0 1 10 20 1 2 30 40
What is the output of:
pd.melt(df, id_vars=['ID'], var_name='Month', value_name='Sales')
Solution
Step 1: Understand melt() parameters
id_vars=['ID'] keeps 'ID' fixed. var_name='Month' renames the variable column. value_name='Sales' renames the value column.Step 2: Predict output structure
Jan and Feb columns become rows under 'Month' with their values under 'Sales'. Result has 4 rows (2 IDs x 2 months).Final Answer:
DataFrame with columns: ID, Month, Sales and 4 rows unpivoted from Jan and Feb -> Option BQuick Check:
melt() output = long format with renamed columns [OK]
- Expecting original wide format output
- Ignoring var_name and value_name renaming
- Thinking melt() drops id_vars
df = pd.DataFrame({'ID':[1,2],'A':[10,20],'B':[30,40]})
result = pd.melt(df, id_vars=['A'], value_vars=['ID', 'B'])What is the main issue with this code?
Solution
Step 1: Analyze id_vars and value_vars roles
id_vars should be columns to keep fixed (usually identifiers). value_vars are columns to unpivot.Step 2: Check column roles in code
'ID' is usually an identifier and should be in id_vars, but here it is in value_vars, which is unusual and likely a mistake.Final Answer:
value_vars contains 'ID' which is usually an identifier and should be in id_vars. -> Option DQuick Check:
Identifiers belong in id_vars, not value_vars [OK]
- Swapping id_vars and value_vars
- Assuming melt() ignores column roles
- Thinking code has syntax error
['Date', 'Store', 'Product_A', 'Product_B']. You want to reshape it so each row shows Date, Store, Product (either 'Product_A' or 'Product_B'), and Sales (the value). Which melt() call achieves this?Solution
Step 1: Identify fixed and unpivot columns
'Date' and 'Store' are identifiers to keep fixed (id_vars). 'Product_A' and 'Product_B' are value columns to unpivot.Step 2: Use melt() with correct parameters
Use id_vars=['Date', 'Store'], var_name='Product' to name the unpivoted column, and value_name='Sales' for values.Final Answer:
pd.melt(df, id_vars=['Date', 'Store'], var_name='Product', value_name='Sales') -> Option AQuick Check:
Keep identifiers fixed, unpivot product columns [OK]
- Putting product columns in id_vars
- Unpivoting identifier columns
- Not renaming var_name or value_name for clarity
Ready to prove it?
Pass the test and this pattern moves unknown
