繁体   English   中英

使用 pandas(附加)将 Dataframe 更改保存到同一个 xlsx 文件

[英]Save Dataframe changes to the same xlsx file using pandas (append)

尝试将更改保存到同一个 xlsx 文件而不覆盖它,

我用什么来读取文件

import pandas as pd 

file = 'path'
df = pd.read_excel(f"{file}", 'sheet')

这已经覆盖了我的文件

df.to_excel(path)

根据 Pandas 团队,可以使用以下内容

https://github.com/pandas-dev/pandas/blob/main/pandas/io/excel/_base.py#L800-L814

 mode : {{'w', 'a'}}, default 'w'
        File mode to use (write or append). Append does not work with fsspec URLs.
    {storage_options}
        .. versionadded:: 1.2.0
    if_sheet_exists : {{'error', 'new', 'replace', 'overlay'}}, default 'error'
        How to behave when trying to write to a sheet that already
        exists (append mode only).
        * error: raise a ValueError.
        * new: Create a new sheet, with a name determined by the engine.
        * replace: Delete the contents of the sheet before writing to it.
        * overlay: Write contents to the existing sheet without removing the old
          contents.

如果有人可以指导我解决这个问题,我将不胜感激:)

我实际上浏览了文档并弄清楚了..我猜我在这里问这个问题太仓促了

将解决方案留在这里,希望它能帮助别人

with pd.ExcelWriter(file,
engine="openpyxl", mode="a", if_sheet_exists="overlay") as writer:
df.to_excel(writer, sheet_name=f"{sheets[counter]}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM