【发布时间】:2020-04-22 08:57:02
【问题描述】:
我正在尝试将来自不同 Excel 文件的多张工作表合并到一个数据框中。所有文件都有多个工作表,其中一张工作表在所有文件中具有相同的名称 - 这是我有兴趣组合成一个数据框的工作表。所有文件都在同一个目录中。
import pandas as pd
import os, glob
os.chdir(r'c:\Users\Documents\Files')
def files(): #to select the files that have RMP and WE on their name
list_files= pd.Series()
for file in glob.glob('RMP*WE*'):
data= pd.Series(file)
list_files= list_files.append(data, ignore_index=True)
return list_files
a= files()
print("This is the variable a\n", a)
def extract_tab(): #to concatenate the sheet called Metrics that all files have
frame_files= pd.DataFrame()
try:
for file in a:
data= pd.read_excel(file,sheet_name='Metrics')
frame_files= frame_files.append(data, ignore_index=True)
except:
pass
return frame_files
b= extract_tab()
print("This is b\n",b)
变量 a(files 函数)的结果是符合命名标准的文件列表。但是变量 b (extract_tab 函数)的结果是一个空数据框。我做错了什么?
我查看了这个帖子Import multiple excel files into python pandas and concatenate them into one dataframe,但它不起作用......虽然我确实从中获得了一些想法。
【问题讨论】:
-
Datanovice 的回答很棒。但我认为您的实现的真正问题是您将文件路径转换为 pd.series
-
@theletz 你有什么建议来解决我选择文件的方式?