简体   繁体   English

Pandas df.to_excel 用于多个 dfs?

[英]Pandas df.to_excel for multiple dfs?

So I want to save 2 dataframes into 2 different worksheets, but the same file.所以我想将 2 个数据框保存到 2 个不同的工作表中,但是是同一个文件。 My code for this part is:我这部分的代码是:

df.to_excel(path, sheet name = 'sheet1')
df2.to_excel(path, sheet name = 'sheet2')

And for some reason the code ignores the first part, the excel file only has sheet2 with df2 on it, sheet1 is nowhere to be found.由于某种原因,代码忽略了第一部分,excel 文件只有 sheet2 和 df2,而 sheet1 无处可寻。 Before I added the df2 part the code saved the df perfectly fine.在我添加 df2 部分之前,代码完美地保存了 df。 Why is that, how could I fix this?为什么会这样,我该如何解决这个问题?

You can use a writer for this:您可以为此使用作家:

with pd.ExcelWriter(output_file) as writer:
    for i,df in enumerate(list_of_dfs, start=1):
        df.to_excel(writer, sheet_name= 'sheet'+str(i))

    writer.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM