如何使用Pandas的melt方法将宽数据框转为长格式?
Pandas 宽表转长表(使用melt函数)
你完全找对方向了,Pandas的melt()函数就是处理这类宽表转长表需求的最佳工具。以下是具体操作步骤:
1. 准备示例数据(模拟你的原始数据框)
首先,我们先创建一个和你提供的格式一致的示例数据框:
import pandas as pd data = { "Store Name": ["Store 1", "Store 2", "Store 3"], "8/7": [2.3, 5.6, 3.4], "8/14": [4.5, 6.4, 5.7], "8/21": [6.4, 5.4, 5.3], "8/28": [6.5, 4.3, 7.8] } df = pd.DataFrame(data)
2. 使用melt函数转换格式
调用melt()函数时,我们需要指定三个核心参数:
id_vars: 不需要被转换的标识符列(这里是Store Name)var_name: 转换后日期列的名称(对应目标格式的Date)value_name: 转换后数值列的名称(对应目标格式的Value)
最后再通过rename()把Store Name列改成Store,完全匹配你想要的格式:
long_df = pd.melt( df, id_vars="Store Name", var_name="Date", value_name="Value" ).rename(columns={"Store Name": "Store"})
3. 转换后的结果
运行上述代码后,long_df的输出就是你需要的长格式:
Date Store Value 0 8/7 Store 1 2.3 1 8/7 Store 2 5.6 2 8/7 Store 3 3.4 3 8/14 Store 1 4.5 4 8/14 Store 2 6.4 5 8/14 Store 3 5.7 6 8/21 Store 1 6.4 7 8/21 Store 2 5.4 8 8/21 Store 3 5.3 9 8/28 Store 1 6.5 10 8/28 Store 2 4.3 11 8/28 Store 3 7.8
内容的提问来源于stack exchange,提问作者Benjamin Parsons
相关产品推荐
相关产品推荐

