LeetCode 题解工作台
重塑数据:融合
DataFrame report +-------------+--------+ | Column Name | Type | +-------------+--------+ | product | object | | quarter_1 | int | | quarter_2 | int |…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Reshape Data: Melt core interview pattern
答案摘要
import pandas as pd def meltTable(report: pd.DataFrame) -> pd.DataFrame:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Reshape Data: Melt core interview pattern 题型思路
题目描述
DataFrame report
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| product | object |
| quarter_1 | int |
| quarter_2 | int |
| quarter_3 | int |
| quarter_4 | int |
+-------------+--------+
编写一个解决方案,将数据 重塑 成每一行表示特定季度产品销售数据的形式。
结果格式如下例所示:
示例 1:
输入: +-------------+-----------+-----------+-----------+-----------+ | product | quarter_1 | quarter_2 | quarter_3 | quarter_4 | +-------------+-----------+-----------+-----------+-----------+ | Umbrella | 417 | 224 | 379 | 611 | | SleepingBag | 800 | 936 | 93 | 875 | +-------------+-----------+-----------+-----------+-----------+ 输出: +-------------+-----------+-------+ | 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 已从宽格式重塑为长格式。每一行表示一个季度内产品的销售情况。
解题思路
方法一
import pandas as pd
def meltTable(report: pd.DataFrame) -> pd.DataFrame:
return pd.melt(report, id_vars=['product'], var_name='quarter', value_name='sales')
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to recognize and use pandas functions like melt to solve data manipulation problems.
- question_mark
Knowledge of handling data reshaping and formatting within DataFrames.
- question_mark
Familiarity with memory and time efficiency concerns in data transformation tasks.
常见陷阱
外企场景- error
Failing to rename the columns correctly after using melt, leading to incorrect output format.
- error
Not understanding the difference between wide and long formats, causing confusion during transformation.
- error
Not considering the potential memory and time complexity when dealing with large datasets.
进阶变体
外企场景- arrow_right_alt
Reshaping data with different column structures, such as additional product attributes.
- arrow_right_alt
Working with larger datasets where efficiency becomes a significant concern.
- arrow_right_alt
Handling more complex data structures with hierarchical index levels or multi-index DataFrames.