首页 > 解决方案 > 循环/迭代excel文件目录并添加到数据框的底部

问题描述

我目前正在使用 Python 导入和格式化大量的 excel 文件(格式/方案相同,但值不同)。

我已经读入并格式化了一个文件,到目前为止一切正常。我现在将对所有其他文件执行相同的操作,并将所有内容合并到一个数据框中,即在一个数据框中读取第一个 excel,在数据框底部添加第二个,在数据框底部添加第三个,依此类推直到我在一个数据框中拥有所有 excel 文件。

到目前为止,我的脚本看起来像这样:

import pandas as pd
import numpy as np
import xlrd
import os

path = os.getcwd()
path = "path of the directory"
wbname = "name of the excel file"
files = os.listdir(path)
files
wb = xlrd.open_workbook(path + wbname)

# I only need the second sheet
df = pd.read_excel(path + wbname, sheet_name="sheet2", skiprows = 2, header = None, 
            skipfooter=132)

# here is where all the formatting is happening ...

df

因此,“文件”是一个包含所有文件相关名称的列表。现在我必须尝试将一个文件一个接一个地放入一个循环中(?),以便它们最终都以 df 结尾。

有没有人做过这样的事情或者可以在这里帮助我。

标签: pythonexcelpandasdataframedirectory

解决方案


像这样的东西可能会起作用:

import os
import pandas as pd
list_dfs=[]
for file in os.listdir('path_to_all_xlsx'):
    df = pd.read_excel(file, <the rest of your config to parse>)
    list_dfs.append(df)

all_dfs = pd.concat(list_dfs)

您读取所有数据帧并将它们添加到列表中,然后 concat 方法将它们全部添加到一个大数据帧中。


推荐阅读