2024-01-09|閱讀時間 ‧ 約 0 分鐘

Reshape Data: Melt 融合不同的資料欄位_Intro to Pandas

題目敘述

題目會給定一個pandas DataFrame作為輸入,要求我們以原有的資料表為基礎,融合不同的資料欄位。

以product作為index,融合quarter_1,quarter_2,quarter_3,quarter_4 這四個欄位,並且重新命名為quarter,並且將數值欄位名稱重新命名為sales。


題目的原文敘述


測試範例

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.

以product作為index,融合quarter_1,quarter_2,quarter_3,quarter_4 這四個欄位,並且重新命名為quarter,
並且將數值欄位名稱重新命名為sales。

演算法

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.