Difficulty: Easy | Acceptance: 85.90% | Paid: No Topics: N/A
Write a solution to reshape the data as shown in the output format.
An output should have the student id, the subject name, and the score for each subject.
- Examples
- Constraints
- Approach 1: Using melt
- Approach 2: Manual Unpivoting with Union
Examples
Example 1
Input:
+-------------+-----------+-----------+-----------+-----------+
| product | quarter_1 | quarter_2 | quarter_3 | quarter_4 |
+-------------+-----------+-----------+-----------+-----------+
| Umbrella | 417 | 224 | 379 | 611 |
| SleepingBag | 800 | 936 | 93 | 875 |
+-------------+-----------+-----------+-----------+-----------+
Output:
+-------------+-----------+-------+
| product | quarter | sales |
+-------------+-----------+-------+
| Umbrella | quarter_1 | 417 |
| SleepingBag | quarter_1 | 800 |
| Umbrella | quarter_2 | 224 |
| SleepingBag | quarter_2 | 936 |
| Umbrella | quarter_3 | 379 |
| SleepingBag | quarter_3 | 93 |
| Umbrella | quarter_4 | 611 |
| SleepingBag | quarter_4 | 875 |
+-------------+-----------+-------+
Explanation: The DataFrame is reshaped from wide to long format. Each row represents the sales of a product in a quarter.
Constraints
2 <= number of rows <= 100
2 <= number of columns <= 100
Approach 1: Using melt
Intuition
The melt function is specifically designed to unpivot a DataFrame from wide format to long format, converting column headers into data values.
Steps
- Identify the identifier column (
student) to keep fixed. - Identify the value columns (
math,physics,chemistry) to unpivot. - Specify the new column names for the unpivoted headers (
subject) and values (score).
python
import pandas as pd
def reshapeData(df: pd.DataFrame) -> pd.DataFrame:
return pd.melt(df, id_vars=['student'], var_name='subject', value_name='score')Complexity
- Time: O(n) where n is the number of cells in the DataFrame.
- Space: O(n) to store the reshaped DataFrame.
- Notes: This is the most idiomatic and efficient approach for this problem.
Approach 2: Manual Unpivoting with Union
Intuition Simulate the melting process by manually selecting each subject column, renaming it appropriately, and then combining (unioning) all the resulting DataFrames.
Steps
- Select the
studentcolumn and the first subject column (e.g.,math). - Rename the subject column to
subject(with literal value ‘math’) and the value column toscore. - Repeat this for all other subject columns.
- Union all the intermediate DataFrames together.
python
import pandas as pd
def reshapeData(df: pd.DataFrame) -> pd.DataFrame:
subjects = ['math', 'physics', 'chemistry']
dfs = []
for sub in subjects:
temp = df[['student']].copy()
temp['subject'] = sub
temp['score'] = df[sub]
dfs.append(temp)
return pd.concat(dfs)Complexity
- Time: O(n * m) where n is rows and m is columns (subjects), as we scan the table multiple times.
- Space: O(n * m) to store the intermediate and final results.
- Notes: More verbose and less efficient than
melt, but demonstrates the underlying mechanics.