我有一個如下所示的資料框
import numpy as np
import pandas as pd
from numpy.random import default_rng
rng = default_rng(100)
cdf = pd.DataFrame({'Id':[1,2,3,4,5],
'customer': rng.choice(list('ACD'),size=(5)),
'region': rng.choice(list('PQRS'),size=(5)),
'dumeel': rng.choice(list('QWER'),size=(5)),
'dumma': rng.choice((1234),size=(5)),
'target': rng.choice([0,1],size=(5))
})
我正在嘗試基于拆分資料框Customer
并將其存盤在檔案夾中。沒有必要理解完整的代碼。問題在最后一行。
i = 0
for k, v in df.groupby(['Customer']):
print(k.split('@')[0])
LM = k.split('@')[0]
i = i 1
unique_cust_names = '_'.join(v['Customer'].astype(str).unique())
unique_ids = '_'.join(v['Id'].astype(str).unique())
unique_location = '_'.join(v['dumeel'].astype(str).unique())
filename = '_'.join([unique_ids, unique_cust_names, unique_location, LM])
print(filename)
with pd.ExcelWriter(f"{filename}.xlsx", engine='xlsxwriter') as writer:
v.to_excel(writer,columns=col_list,index=False)
wb = load_workbook(filename = 'format_sheet.xlsx')
sheet_from =wb.worksheets[0]
wb1 = load_workbook(filename = f"{filename}.xlsx")
sheet_to = wb1.worksheets[0]
copy_styles(sheet_from, sheet_to)
#wb.close()
tab = Table(displayName = "Table1", ref = "A1:" get_column_letter(wb1.worksheets[0].max_column) str(wb1.worksheets[0].max_row) )
style = TableStyleInfo(name="TableStyleMedium2", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False)
tab.tableStyleInfo = style
wb1.worksheets[0].add_table(tab)
#wb1.worksheets[0].parent.save(f"{filename}.xlsx")
wb1.save("test_files/" f"{filename}.xlsx") # issue is here
wb1.close()
print("Total number of customers to be emailed is ", i)
雖然代碼作業正常,但我猜問題出在下面一行
wb1.save("test_files/" f"{filename}.xlsx") # issue is here
這會創建兩個檔案副本。一個在當前檔案夾中作為 jupyter notebook 檔案,另一個在test_files
檔案夾中。
例如:我看到兩個檔案,test1.xlsx
一個在當前檔案夾中,一個在test_files
檔案夾內(路徑是 test_files/test1.xlsx)
我怎樣才能避免這種情況?
我希望我的輸出為檔案夾內的每個客戶只生成/保存 1 個檔案test_files
?
uj5u.com熱心網友回復:
問題正在發生,因為您參考了 2 個不同的檔案名,一個帶有前綴"test_files/"
,一個不帶前綴。處理它的最佳方法是定義檔案名如下
dir_filename = "test_files/" f"{filename}.xlsx"
然后在以下地方參考它
with pd.ExcelWriter(f"{filename}.xlsx", engine='xlsxwriter') as writer:
v.to_excel(writer,columns=col_list,index=False)
##
wb1 = load_workbook(filename = f"{filename}.xlsx")
##
wb1.save("test_files/" f"{filename}.xlsx")
希望能幫助到你
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/505652.html
上一篇:C# 中針對 System.Runtime.InteropServices.ExternalException:“GDI+ 中發生一般性錯誤。”另一種圖片保存方案