簡體   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