pandas df.to_excel用于多个df? [英] Pandas df.to_excel for multiple dfs?

查看:43
本文介绍了 pandas df.to_excel用于多个df?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想将2个数据帧保存到2个不同的工作表中,但文件相同.我这部分的代码是:

So I want to save 2 dataframes into 2 different worksheets, but the same file. My code for this part is:

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

由于某种原因,代码会忽略第一部分,因此excel文件中只有带有df2的sheet2,找不到sheet1.在添加df2部分之前,代码将df保存得非常好.为什么会这样,我该如何解决呢?

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. Before I added the df2 part the code saved the df perfectly fine. 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()

这篇关于 pandas df.to_excel用于多个df?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆