[英]create multiple dataframes in loop and write to excel
我正在一個生成數據幀的函數上運行循環,如下所示:
Prd1 Prd2 Prd3 Prd4 Prd5 Prd6
Loc1 0 0 0 0 0 0
Loc2 0 0 0 0 0 0
Loc3 0 30.61 0 0 319.58 430.87
Loc4 0 0 0 0 0 120.73
Loc5 0 0 0 0 0 0
Loc6 78.21 822.36 0 0 0 0
我想多次運行該函數,生成一系列數據幀,然后分析或可視化隨時間的演變。為此,將它們全部放在一個 Excel 工作簿中是理想的。 但是,我正在為此而苦苦掙扎。 我試過了
for case in CASES:
B= A[case]
result = function(B)
print(result)
with pd.ExcelWriter('results.xlsx') as writer: # doctest: +SKIP
result.to_excel(writer, sheet_name='case_'+str(case))
我希望這會將不同的結果寫入同一個電子表格。 然而,結果電子表格只包含帶有最后一個案例的選項卡。 我可以看到 CASES 循環中的上述內容每次將如何覆蓋現有工作表。 是否有保留已存在的工作表並將任何新工作表“附加”到現有工作簿的功能? 提前致謝。 問候P。
根據這個SO thread ,您可以在開始循環之前檢索工作表名稱列表並檢查現有工作表並跳過它們。
xl = pd.ExcelFile('results.xlsx')
existing_sheets = xl.sheet_names
for case in CASES:
if f'cast_{str(case)}' in existing_sheets:
continue
B= A[case]
result = function(B)
print(result)
with pd.ExcelWriter('results.xlsx') as writer: # doctest: +SKIP
result.to_excel(writer, sheet_name=f'case_{str(case)}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.