[英]Pandas creates new excel sheet when trying to append to existing sheet
I have the code where I want to read data from the current sheet, store it in df_old, append the current data to it using df = df_old.append(df)
and then replace the data in the sheet with this new dataframe. However, what it does instead is create a new sheet with the exact same name where it publishes this new dataframe. I tried adding if_sheet_exists="replace"
as an argument to ExcelWriter but this did not change anything.我有代码,我想从当前工作表中读取数据,将其存储在 df_old 中,append 使用df = df_old.append(df)
将当前数据存储到它,然后用这个新的 dataframe 替换工作表中的数据。但是,相反,它所做的是创建一个名称完全相同的新工作表,并在其中发布这个新的 dataframe。我尝试将if_sheet_exists="replace"
添加为 ExcelWriter 的参数,但这并没有改变任何东西。 How can I force it to overwrite the data in the sheet with the current name?如何强制它用当前名称覆盖工作表中的数据?
df_old = pd.read_excel(r'C:\Users\XXX\Downloads\Digitalisation\mat_flow\reblend_v2.xlsx',sheet_name = ft_tags_final[i][j])
df = df_old.append(df)
with pd.ExcelWriter(r'C:\Users\XXX\Downloads\Digitalisation\mat_flow\reblend_v2.xlsx', engine="openpyxl", mode="a", if_sheet_exists="replace") as writer:
df.to_excel(writer, index=False, sheet_name = ft_tags_final[i][j])
I had the same issue and i solved it with using write
instead of append
.我遇到了同样的问题,我使用write
而不是append
解决了这个问题。 Also i used openpyxl
instead of xlsxwriter
我也用openpyxl
而不是xlsxwriter
from pandas import ExcelWriter
from pandas import ExcelFile
from openpyxl import load_workbook
book = load_workbook('Wallet.xlsx')
writer = pd.ExcelWriter('Wallet.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
#^THIS IS THE MOST IMPORTANT LINES BECAUSE IT GIVES PANDAS THE SHEET
Data.to_excel(writer, sheet_name='Main', header=None, index=False, startcol=number,startrow=counter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.