You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于列值重组Pandas DataFrame并转换为指定结构?

Pandas DataFrame 宽表转长表解决方案

假设你的原始DataFrame结构如下(对应你提供的第一张表):

Product2023-01-012023-01-022023-01-03
Product A101520
Product B5812
Product C369

要转换为第二张表的长表结构(包含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结构如下:

ProductDateQuantity
Product A2023-01-0110
Product A2023-01-0215
Product A2023-01-0320
Product B2023-01-015
Product B2023-01-028
Product B2023-01-0312
Product C2023-01-013
Product C2023-01-026
Product C2023-01-039

内容的提问来源于stack exchange,提问作者Zeeshan Asghar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:25:32