You need to enable JavaScript to run this app. Excel表头字段变化时的Python pandas动态读取方案需求
优惠活动
大模型
产品
解决方案
定价
更多

Excel表头字段变化时的Python pandas动态读取方案需求

需求:统一不同表头的Excel数据提取映射

问题背景

我收到客户发送的materials.xlsx文件,文件包含N行N列,但仅需提取其中12列数据。客户两次发送的文件内容一致,但表头字段不同:

第一次发送的文件表头示例:

materialLong DesRef
11000021Panda toyCotton Toy
11100212Red Panda ToyPlastic Toy

第二次发送的文件表头示例:

InternalDescribeLocation
11000021Panda toyCotton Toy
11100212Red Panda ToyPlastic Toy

当前处理方式

目前我需要手动修改代码中的表头参数或调整Excel表头才能获取目标输出,现有代码如下:

# 适配第一次表头的代码
ds1 = pd.read_excel('Materialsheet.xlsx', usecols=['Material', 'Group', 'Priority', 'Long Des', 'Ref', 'Qty','Shape'],index_col=False) 
ds1 = ds1[['Material', 'Group','Priority','Long Des','Qty','Shape','Ref']]
print(ds1)
# 适配第二次表头的代码
ds = pd.read_excel('Materialsheet.xlsx', usecols=['Internal', 'Alter.Group', 'Priority', 'Describe', 'Location', 'Qty','image'],index_col=False) 

需求目标

编写通用代码,实现将不同源表头(如material、Internal)统一映射为目标字段(如PN),无需手动修改代码适配表头变化。


解决方案

通过定义表头映射字典实现自动适配,具体代码如下:

import pandas as pd

# 定义表头映射:键为所有可能的源表头,值为统一的目标字段
header_mapping = {
    # 物料编号类
    'material': 'PN',
    'Internal': 'PN',
    # 描述类
    'Long Des': 'Description',
    'Describe': 'Description',
    # 分类类
    'Ref': 'Category',
    'Location': 'Category',
    # 其他字段
    'Group': 'Group',
    'Alter.Group': 'Group',
    'Priority': 'Priority',
    'Qty': 'Qty',
    'Shape': 'Shape',
    'image': 'Image'
    # 补充剩余4个目标字段的映射关系即可
}

# 读取Excel原始数据
df_raw = pd.read_excel('materials.xlsx')
# 筛选出映射字典中存在的有效列
valid_cols = [col for col in df_raw.columns if col in header_mapping]
df_filtered = df_raw[valid_cols]

# 重命名表头为统一目标字段
df_renamed = df_filtered.rename(columns=header_mapping)

# 定义目标字段的固定顺序(按你需要的12列顺序排列)
target_columns = ['PN', 'Group', 'Priority', 'Description', 'Qty', 'Shape', 'Category', 'Image']  # 补充剩余字段

# 按目标顺序整理列,缺失字段自动填充NaN
df_final = df_renamed.reindex(columns=target_columns)

print(df_final)

代码说明

  • 表头映射字典:把客户可能用到的所有源表头对应到固定目标字段,后续新增表头只需在字典中补充条目
  • 自动筛选有效列:仅保留需要处理的字段,避免读取无关列
  • 统一表头与列排序:确保最终输出的表头名称、列顺序完全符合需求,无需手动调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:42:42