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

如何用Pandas合并单个工作簿的多Excel工作表并生成标识符列?

合并多Excel工作表并生成标识符列的实现方案

可以用Python的pandas库快速实现这个需求,核心是遍历工作表、提取括号内的标识符、统一列名后合并。

步骤1:安装依赖

首先确保安装了所需的库:

pip install pandas openpyxl

(openpyxl用于处理.xlsx格式文件,若为.xls则替换为xlrd)

步骤2:完整代码实现

import pandas as pd
import re

# 定义函数:从字符串中提取括号内的内容
def get_identifier(text):
    match_result = re.search(r'\((.*?)\)', text)
    return match_result.group(1) if match_result else None

# 替换为你的Excel文件路径
excel_file = "你的工作簿路径.xlsx"
# 读取工作簿
workbook = pd.ExcelFile(excel_file)
# 存储每个工作表处理后的DataFrame
processed_dfs = []

# 遍历工作簿中的每个工作表
for sheet in workbook.sheet_names:
    # 读取当前工作表数据
    df = workbook.parse(sheet)
    
    # 找到表头中带括号的列(假设每个工作表仅有一个此类列)
    try:
        target_column = next(col for col in df.columns if '(' in col and ')' in col)
    except StopIteration:
        print(f"警告:工作表{sheet}未找到带括号的列,已跳过")
        continue
    
    # 提取标识符
    identifier = get_identifier(target_column)
    # 重命名列,移除括号部分以保证合并时列名一致
    clean_col_name = target_column.split('(')[0].strip()
    df.rename(columns={target_column: clean_col_name}, inplace=True)
    
    # 添加identifier列
    df['identifier'] = identifier
    # 调整列顺序,将identifier放在最前面
    df = df[['identifier'] + [col for col in df.columns if col != 'identifier']]
    
    # 将处理后的DataFrame加入列表
    processed_dfs.append(df)

# 纵向合并所有工作表数据
final_result = pd.concat(processed_dfs, ignore_index=True)

# 输出结果或保存到文件
print(final_result)
final_result.to_excel("合并后的结果.xlsx", index=False)

关键逻辑说明

  1. 标识符提取:用正则表达式r'\((.*?)\)'匹配括号内的内容,非贪婪模式确保只提取一对括号内的文本。
  2. 列名统一:将带括号的列名(如d(Connect))重命名为d,避免合并时因列名不一致导致的列错位。
  3. 异常处理:加入try-except捕获找不到带括号列的情况,避免程序崩溃。
  4. 合并数据:用pd.concat纵向合并所有处理后的DataFrame,ignore_index=True重置索引保证行号连续。

自定义调整

  • 如果工作表中有多个带括号的列,可以修改target_column的查找逻辑,比如指定列的位置(如df.columns[3])或匹配特定前缀。
  • 如果需要对标识符做额外处理(如补全Connect1的数字),可以在提取后添加逻辑(如identifier = f"{identifier}1")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:40:34