如何基于列值重组Pandas DataFrame并转换为指定结构?
Pandas DataFrame 宽表转长表解决方案
假设你的原始DataFrame结构如下(对应你提供的第一张表):
| Product | 2023-01-01 | 2023-01-02 | 2023-01-03 |
|---|---|---|---|
| Product A | 10 | 15 | 20 |
| Product B | 5 | 8 | 12 |
| Product C | 3 | 6 | 9 |
要转换为第二张表的长表结构(包含Product、Date、Quantity三列),可以用以下两种实用方法:
方法1:使用pd.melt()函数
这是宽表转长表的标准方法,指定保留的标识列、新列的名称即可:
import pandas as pd # 假设原始DataFrame变量名为df df_long = pd.melt(df, id_vars=['Product'], var_name='Date', value_name='Quantity')
方法2:使用stack()方法
通过索引堆叠实现转换,步骤清晰直观:
# 设置Product为索引,堆叠日期列后重置索引并命名列 df_long = df.set_index('Product').stack().reset_index() df_long.columns = ['Product', 'Date', 'Quantity']
转换后的DataFrame结构如下:
| Product | Date | Quantity |
|---|---|---|
| Product A | 2023-01-01 | 10 |
| Product A | 2023-01-02 | 15 |
| Product A | 2023-01-03 | 20 |
| Product B | 2023-01-01 | 5 |
| Product B | 2023-01-02 | 8 |
| Product B | 2023-01-03 | 12 |
| Product C | 2023-01-01 | 3 |
| Product C | 2023-01-02 | 6 |
| Product C | 2023-01-03 | 9 |
内容的提问来源于stack exchange,提问作者Zeeshan Asghar
相关产品推荐
相关产品推荐

