Pandas合并多份Excel文件时如何新增列记录对应源文件名
代码修改方案
你只需要在每次读取单个Excel文件后,为当前读取到的临时数据表新增一列存储当前文件名,再合并到总表即可。修改后的完整代码如下:
import os import pandas as pd cwd = os.path.abspath('') files = os.listdir(cwd) ## Code gets the first sheet of a given file df = pd.DataFrame() for file in files: if file.endswith('.xlsx'): # 读取当前Excel文件到临时表 temp_df = pd.read_excel(file) # 新增源文件名列 temp_df['source_filename'] = file # 合并到总表 df = pd.concat([df, temp_df], ignore_index=True) df.head() # 导出时加index=False避免输出多余索引列,不需要可删除 df.to_excel('Combined.xlsx', index=False)
补充说明
- 这里将原代码中已被pandas 2.0+版本废弃的
append方法替换为官方推荐的pd.concat写法,兼容新旧版本的pandas库 - 如果不需要保留文件名的
.xlsx后缀,可将新增列的代码替换为temp_df['source_filename'] = os.path.splitext(file)[0],就能得到无后缀的源文件名
内容的提问来源于stack exchange,提问作者AntonioIBC
相关产品推荐
相关产品推荐

