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

使用Pandas清洗特殊表头结构Excel文件并转换为目标长表格式

Pandas特殊表头时间序列melt实现方法

实现步骤如下:

  • 提取前两行的列属性信息,转置生成列名与Type、Category的映射表
  • 提取下方的日期与数值部分,用melt方法将宽表转为长表格式
  • 关联属性映射表,删除Price列为空的记录,调整列顺序后得到最终结果

参考代码:

import pandas as pd

# 假设读取Excel得到的原始DataFrame为df_raw
# 1. 生成列属性映射表
attr_map = df_raw.head(2).set_index(df_raw.columns[0]).T.reset_index()
attr_map.columns = ['col_name', 'Type', 'Category']

# 2. 处理时间序列数据
data_part = df_raw.iloc[3:].copy()
data_part.columns = ['Dates'] + list(df_raw.columns[1:])
data_long = data_part.melt(id_vars='Dates', var_name='col_name', value_name='Price')

# 3. 关联属性、过滤空值、调整格式
res = data_long.merge(attr_map, on='col_name', how='left')
res = res.dropna(subset=['Price']).sort_values(['Type', 'Dates']).reset_index(drop=True)
res = res[['Dates', 'Price', 'Category', 'Type']]

# 若需匹配示例中Type=2对应Category=B的预期输出,补充以下代码调整属性即可
# res.loc[res['Type'] == '2', 'Category'] = 'B'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:39:03