【问题标题】:How to reformat the resultant excel sheet after coming multiple excel sheet in Pandas Python如何在 Pandas Python 中出现多个 excel 表后重新格式化生成的 excel 表
【发布时间】:2020-06-03 20:09:09
【问题描述】:

我尝试使用 pandas python 将多个 excel 的多个工作表组合成单个 excel,但在最后的 excel 工作表中,行标签是 excel 工作表文件名,每个工作表作为列名。我觉得它很乱。

如何以正确的格式获取它。代码如下:

import pandas as pd
import os
from openpyxl.workbook import Workbook

os.chdir("C:/Users/w8/PycharmProjects/decorators_exaample/excel_files")

path = "C:/Users/w8/PycharmProjects/decorators_exaample/excel_files"
files = os.listdir(path)

AllFiles = pd.DataFrame()

for f in files:
    info = pd.read_excel(f, sheet_name=None)
    AllFiles=AllFiles.append(info, ignore_index=True)



writer = pd.ExcelWriter("Final.xlsx")
AllFiles.to_excel(writer)
writer.save()

最终的 excel 看起来像这样: enter image description here

【问题讨论】:

    标签: python-3.x excel pandas


    【解决方案1】:

    您实际上并不需要整个操作系统和工作簿部分。这可以清理您的代码并轻松查找错误。我假设,path 是存储所有 excel 文件的文件夹的路径:

    import pandas as pd
    import glob
    
    path = "C:\Users\w8\PycharmProjects\decorators_exaample\excel_files"
    file_list = glob.glob(path)
    
    df= pd.DataFrame()
    
    for f in file_list :
        info = pd.read_excel(f)
        df = df.append(info)
    
    df.to_excel('C:\Users\w8\PycharmProjects\decorators_exaample\excel_files\new_filename.xlsx')
    

    应该就这么简单

    【讨论】:

    • 反斜杠导致了问题。我尝试了正斜杠,但我收到了这个错误:Traceback(最近一次调用最后一次):文件“C:/Users/w8/PycharmProjects/decorators_exaample/decorator_example.py” ,第 10 行,在 info = pd.read_excel(f) 文件“C:\Users\w8\PycharmProjects\decorators_exaample\venv\lib\site-packages\pandas\io\excel_base.py”中,第 304 行read_excel io = ExcelFile(io, engine=engine) 文件“C:\Users\w8\PycharmProjects\decorators_exaample\venv\lib\site-packages\pandas\io\excel_base.py”,第 824 行,在 init self._reader = self._engines[engine](self
    • 那么你的问题解决了吗?您是否尝试过建议的解决方案?如果是这样,它对你有用吗?
    • 不,没有。无论如何我的前辈说我会调查一下。谢谢@TiTo的回答
    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 2018-07-25
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2019-06-25
    相关资源
    最近更新 更多