Skip to main content
 首页 » 编程设计

python之将多个 excel 文件导入 pandas 并根据文件名创建一列

2024年12月31日7jiqing9006

我在一个文件夹中有多个 excel 文件,我想读取它们并将它们连接在一起,但是在连接在一起时我想根据文件名添加列

'D:\\156667_Report.xls', 
'D:\\192059_Report.xls', 
'D:\\254787_Report.xls', 
'D:\\263421_Report.xls', 
'D:\\273554_Report.xls', 
'D:\\280163_Report.xls', 
'D:\\307928_Report.xls' 

我可以使用以下脚本在 pandas 中读取这些文件

path =r'D:\' # use your path 
allFiles = glob.glob(path + "/*.xls") 
frame = pd.DataFrame() 
list_ = [] 
for file_ in allFiles: 
   df = pd.read_excel(file_,index_col=None, header=0) 
   list_.append(df) 
 
frame = pd.concat(list_) 

我想在我阅读的所有文件中添加列作为 代码。代码将是文件名中的数字,例如156667,192059

请您参考如下方法:

为什么不匹配

foo = re.match('\.*_Report', file_) 
num = foo[:6]` 
df['Code']= num 

在你的循环中?