Append/Concatenate 多重 excel 数据集使用 for 循环 (Python)

Append/Concatenate multipe excel data sets using for loop (Python)

我正在尝试更有效地合并来自模拟的数据 运行。目前,根据 运行 集,数据在不同文件夹中的多个 excel 文档中生成。

要选择我传递此代码的文件:

def XLFiles():
    root = Tkinter.Tk()
    root.withdraw()
    select_files = tkFileDialog.askopenfilenames(parent=root, initialdir='dir', title='Choose Rig Data Files')
    return select_files

select_files = XLFiles()
file_list = list(select_files)

这 return 是相关文档的所有目录的列表。

接下来我打算将数据合并在一起。这是我遇到问题的地方。

我用过:

df2 = []

for f in list(select_files):
    df1 = pd.read_excel(f, header=1, skiprows=range(2,50), usecols="H,I")
    df2.append(df1)

我的问题是这不是 return 数据框,而是 3 个列表。我假设是因为我做了 'df2=[]' 但是我不知道如何将 df2 创建为没有任何数据的数据框。请你能把我推向正确的方向吗?

谢谢

试试这个:

df = pd.concat([pd.read_excel(f, header=1, skiprows=range(2,50), usecols="H,I")
                for f in select_files], ignore_index=True)

您需要 DataFrame 列表的 concat,如果连接为空 DataFrame 则没有错误:

df2 = []
for f in list(select_files):
    df1 = pd.read_excel(f, header=1, skiprows=range(2,50), usecols="H,I")
    df2.append(df1)
df = pd.concat(df2, ignore_index=True)