Reshape Data: Melt - Problem
You are given a DataFrame report with the following schema:
| Column Name | Type |
|---|---|
| product | object |
| quarter_1 | int |
| quarter_2 | int |
| quarter_3 | int |
| quarter_4 | int |
Write a solution to reshape the data so that each row represents sales data for a product in a specific quarter.
The result should transform wide format data (quarters as columns) into long format data (quarters as rows), where each product appears multiple times - once for each quarter with its corresponding sales value.
Input & Output
Example 1 — Basic Reshape
$
Input:
data = [{"product": "A", "quarter_1": 100, "quarter_2": 200, "quarter_3": 150, "quarter_4": 180}]
›
Output:
[{"product": "A", "quarter": "quarter_1", "sales": 100}, {"product": "A", "quarter": "quarter_2", "sales": 200}, {"product": "A", "quarter": "quarter_3", "sales": 150}, {"product": "A", "quarter": "quarter_4", "sales": 180}]
💡 Note:
Product A's quarterly sales are reshaped from columns to rows: each quarter becomes a separate record
Example 2 — Multiple Products
$
Input:
data = [{"product": "A", "quarter_1": 100, "quarter_2": 200, "quarter_3": 150, "quarter_4": 180}, {"product": "B", "quarter_1": 120, "quarter_2": 180, "quarter_3": 160, "quarter_4": 200}]
›
Output:
[{"product": "A", "quarter": "quarter_1", "sales": 100}, {"product": "A", "quarter": "quarter_2", "sales": 200}, {"product": "A", "quarter": "quarter_3", "sales": 150}, {"product": "A", "quarter": "quarter_4", "sales": 180}, {"product": "B", "quarter": "quarter_1", "sales": 120}, {"product": "B", "quarter": "quarter_2", "sales": 180}, {"product": "B", "quarter": "quarter_3", "sales": 160}, {"product": "B", "quarter": "quarter_4", "sales": 200}]
💡 Note:
Two products become 8 rows total: each product contributes 4 quarter records
Example 3 — Zero Sales
$
Input:
data = [{"product": "C", "quarter_1": 0, "quarter_2": 50, "quarter_3": 0, "quarter_4": 75}]
›
Output:
[{"product": "C", "quarter": "quarter_1", "sales": 0}, {"product": "C", "quarter": "quarter_2", "sales": 50}, {"product": "C", "quarter": "quarter_3", "sales": 0}, {"product": "C", "quarter": "quarter_4", "sales": 75}]
💡 Note:
Even zero sales values are preserved in the melted format
Constraints
- 1 ≤ data.length ≤ 1000
- Product names are non-empty strings
- Sales values are non-negative integers
Visualization
Tap to expand
Understanding the Visualization
1
Input Wide Format
DataFrame with products and quarterly columns
2
Melt Operation
Unpivot quarter columns into rows
3
Output Long Format
Each product-quarter combination as separate row
Key Takeaway
🎯 Key Insight: Melt operation unpivots columns into rows, creating a normalized data structure perfect for analysis
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code