[英]Appending multiple dataframes to excel on different sheets
我想將字典中的多個數據框添加到一個 excel 文件中,並且每個數據框都應該寫在一張表中。 光澤名稱實際上是字典的關鍵。 以下代碼
for key in df_dict:
df = df_dict[key]
df.to_excel('data-frames.xlsx', sheet_name=key, index=False)
只寫入最后一個數據幀。 所以,我只看到一張紙。 另一方面,此處描述的append_df_to_excel()
方法不起作用。 我得到沒有這種方法的錯誤,雖然熊貓版本是 1.4.2。
...
AttributeError: 'DataFrame' object has no attribute 'append_df_to_excel'
In [2]: import pandas as pd
In [2]: print(pd.__version__)
1.4.2
我該如何解決?
你能試試這個代碼嗎?
for key in df_dict:
df = df_dict[key].copy()
with pd.ExcelWriter('data-frames.xlsx', mode='a') as writer:
df.to_excel(writer, sheet_name=key)
這是一種執行您所要求的方法:
import pandas as pd
df_dict = {f'key_{i}':pd.DataFrame([[i+1,i+2,i+3],['a','b','c']], columns=['first','second','third']) for i in range(4)}
[print(f'{k}:\n{df}') for k, df in df_dict.items()]
with pd.ExcelWriter('TestOutput.xlsx') as writer:
for sheet, df in df_dict.items():
df.to_excel(writer, index=None, sheet_name=sheet)
輸入
key_0:
first second third
0 1 2 3
1 a b c
key_1:
first second third
0 2 3 4
1 a b c
key_2:
first second third
0 3 4 5
1 a b c
key_3:
first second third
0 4 5 6
1 a b c
輸出
Excel 文件
TestOutput.xlsx
包含四個名為key_1
、key_1
、key_3
和key_4
的工作表,每個工作表包含名為first
、second
和third
的 3 列以及兩行數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.