DataFrame report
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| product | object |
| quarter_1 | int |
| quarter_2 | int |
| quarter_3 | int |
| quarter_4 | int |
+-------------+--------+
이 문제는 "각 행이 특정 분기(quarter)마다 제품의 판매 데이터를 나타내도록 데이터를 재구성하는 문제"입니다.
즉, 제품별로 분기별 판매 데이터를 분리하여 새로운 형식으로 변환해야 합니다.
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 |
+-------------+-----------+-------+
해석:
이 설명은 DataFrame이 'wide format'에서 'long format'으로 변환되었다는 의미입니다.
'Wide format'은 여러 개의 열을 사용하여 데이터를 표현하는 형식이고, 'Long format'은 각 행(row)이 특정 항목에 대한 값을 나타내는 형식입니다.
정답
import pandas as pd
def meltTable(report: pd.DataFrame) -> pd.DataFrame:
df_melted = pd.melt(report, id_vars=['product'], var_name='quarter', value_name='sales')
return df_melted
개념 정리
Melt() 란? 컬럼을 행으로 보내는 함수
예시 데이터 프레임 df
name | test1 | test2 | test3 |
jojo | t1_a | t2_a | t3_a |
dodo | t1_b | t2_b | t3_b |
pd.melt(df, id_vars=['name'], var_name='test', value_name='t_value'
name | test | t_value |
jojo | test1 | t1_a |
dodo | test1 | t1_b |
jojo | test2 | t2_a |
dodo | test2 | t2_b |
jojo | test3 | t3_a |
dodo | test3 | t3_b |
이와 같이 컬럼명을 행으로 넣고 그 컬럼의 값을 다시 행의 값으로 재 배열을 할 수 있다
'[코딩테스트] > [Pandas]' 카테고리의 다른 글
[LeetCode - Pandas] (Easy) 2888. Reshape Data: Concatenate (0) | 2025.03.27 |
---|---|
[LeetCode - Pandas] (Easy) 2889. Reshape Data: Pivot (0) | 2025.03.27 |
[LeetCode - Pandas] (Easy) 2891. Method Chaining (0) | 2025.03.26 |
[LeetCode - Pandas] (Easy) 3436. Find Valid Emails (0) | 2025.03.25 |
[LeetCode - Pandas] (Easy) 3465. Find Products with Valid Serial Numbers (0) | 2025.03.25 |