繁体   English   中英

如何在不发生此错误的情况下将多个数据框保存到一个 Excel 文件(作为单独的工作表)中?

[英]How can I save multiple dataframes onto one excel file (as separate sheets) without this error occurring?

我有以下 Python 代码:

import pandas as pd
path=r"C:\Users\Wali\Example.xls"
df1=pd.read_excel(path, sheet_name = [0])
df2=pd.read_excel(path, sheet_name = [1])

with pd.ExcelWriter(r"C:\Users\Wali\Example2.xls") as writer:

    # use to_excel function and specify the sheet_name and index
    # to store the dataframe in specified sheet
    df1.to_excel(writer, sheet_name="1", index=0)
    df2.to_excel(writer, sheet_name="2", index=1)

我正在阅读包含两张工作表的 excel 文件,然后将这些工作表保存到一个新的 excel 文件中,但不幸的是我收到以下错误:

AttributeError: 'dict' object has no attribute 'to_excel'

关于如何解决这个问题的任何想法? 谢谢。

将 pd.read_excel(path, sheet_name = [0]) 中的 [0] 更改为 0 将解决此问题

import pandas as pd
path=r"test_book.xlsx"
df1=pd.read_excel(path, sheet_name = 0)
df2=pd.read_excel(path, sheet_name = 1)

with pd.ExcelWriter(r"test_book1.xlsx") as writer:

    # use to_excel function and specify the sheet_name and index
    # to store the dataframe in specified sheet
    df1.to_excel(writer, sheet_name="1", index=0)
    df2.to_excel(writer, sheet_name="2", index=1)

暂无
暂无

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

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