python - 使用 Pandas 在python中循环遍历多个excel文件

标签 python excel for-loop pandas

我知道这种类型的问题一直被问到。但我无法找到执行此操作的最佳方法。

我编写了一个脚本,使用 pandas 重新格式化单个 excel 文件。 效果很好。

现在我想遍历多个 excel 文件,执行相同的重新格式化,并将每个 excel 工作表中新重新格式化的数据一个接一个地放在底部。

我相信第一步是列出目录中的所有 excel 文件。 有很多不同的方法可以做到这一点,所以我很难找到最好的方法。

下面是我目前用来导入多个 .xlsx 并创建列表的代码。

import os
import glob

os.chdir('C:\ExcelWorkbooksFolder')
for FileList in glob.glob('*.xlsx'):
         print(FileList)

我不确定之前的 glob 代码是否真的创建了我需要的列表。

然后我很难理解从那里去哪里。 下面的代码在 pd.ExcelFile(File) 处失败 我相信我错过了一些东西....

# create for loop
for File in FileList:
    for x in File:
# Import the excel file and call it xlsx_file
xlsx_file = pd.ExcelFile(File)
xlsx_file
# View the excel files sheet names
xlsx_file.sheet_names
# Load the xlsx files Data sheet as a dataframe
df = xlsx_file.parse('Data',header= None)
# select important rows,
df_NoHeader = df[4:]
#then It does some more reformatting.
'

非常感谢任何帮助

最佳答案

我解决了我的问题。我没有使用 glob 函数,而是使用 os.listdir 读取我所有的 excel 工作表,遍历每个 excel 文件,重新格式化,然后将最终数据附加到表的末尾。

#first create empty appended_data table to store the info.
appended_data = []


for WorkingFile in os.listdir('C:\ExcelFiles'):
     if os.path.isfile(WorkingFile):

        # Import the excel file and call it xlsx_file
        xlsx_file = pd.ExcelFile(WorkingFile)
        # View the excel files sheet names
        xlsx_file.sheet_names
        # Load the xlsx files Data sheet as a dataframe
        df = xlsx_file.parse('sheet1',header= None)

        #.... do so reformating, call finished sheet reformatedDataSheet
        reformatedDataSheet
        appended_data.append(reformatedDataSheet)
appended_data = pd.concat(appended_data)

就是这样,它完成了我想要的一切。

关于python - 使用 Pandas 在python中循环遍历多个excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397037/

相关文章:

python - PropertyMock 的 side_effect 函数仅被调用一次

Python Kubernetes 客户端 : equivalent of kubectl get [custom-resource]

读取 ExcelWorksheet 时出现 C# ArgumentOutOfRangeException

sql-server - 在Excel中的VBA中捕获来自SQL Server的错误消息

Java - 从列表中显示 n 组记录?

python - 结合 Python List 和 Dict comprehension with counter

Python 代码可以在 Windows 中运行,但不能在 Linux 中运行

excel - 如何使用偏移量使用 VBA 扩展命名范围

Windows 7 剩余的批处理文件参数

python - Python 嵌套 For 循环错误