简体   繁体   English

append dataframe 到 excel 与 Z3A43B4F88325D94022C0EFA9C2FA2F5

[英]append dataframe to excel with pandas

I desire to append dataframe to excel我希望 append dataframe 到 excel

This code works nearly as desire.该代码几乎可以按预期工作。 Though it does not append each time.虽然不是每次都 append。 I run it and it puts data-frame in excel.我运行它并将数据帧放入 excel。 But each time I run it it does not append.但是每次我运行它时它都不会 append。 I also hear openpyxl is cpu intensive but not hear of many workarounds .我还听说 openpyxl 是 cpu 密集型的,但没有听说过很多解决方法

import pandas
from openpyxl import load_workbook

book = load_workbook('C:\\OCC.xlsx')
writer = pandas.ExcelWriter('C:\\OCC.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

df1.to_excel(writer, index = False)

writer.save()

I want the data to append each time I run it, this is not happening.每次我运行它时,我都希望数据到 append,这不会发生。

Data output looks like original data:数据 output 看起来像原始数据:

A   B   C
H   H   H

I want after run a second time我想在第二次运行后

A   B    C
H   H    H
H   H    H

Apologies if this is obvious I new to python and examples I practise did not work as wanted.如果这很明显我是 python 的新手,并且我练习的示例没有按预期工作,请道歉。

Question is - how can I append data each time I run.问题是 - 我每次运行时如何 append 数据。 I try change to xlsxwriter but get AttributeError: 'Workbook' object has no attribute 'add_format'我尝试更改为 xlsxwriter 但得到AttributeError: 'Workbook' object has no attribute 'add_format'

first of all, this post is the first piece of the solution, where you should specify startrow= : Append existing excel sheet with new dataframe using python pandas首先,这篇文章是解决方案的第一部分,您应该在其中指定startrow=使用 python pandas 使用新的数据startrow= 附加现有的 excel 表

you might also consider header=False .您也可以考虑header=False so it should look like:所以它应该看起来像:

df1.to_excel(writer, startrow = 2,index = False, Header = False)

if you want it to automatically get to the end of the sheet and append your df then use:如果您希望它自动到达工作表的末尾并附加您的 df 则使用:

startrow = writer.sheets['Sheet1'].max_row

and if you want it to go over all of the sheets in the workbook:如果您希望它遍历工作簿中的所有工作表:

for sheetname in writer.sheets:
    df1.to_excel(writer,sheet_name=sheetname, startrow=writer.sheets[sheetname].max_row, index = False,header= False)

btw: for the writer.sheets you could use dictionary comprehension (I think it's more clean, but that's up to you, it produces the same output):顺便说一句:对于writer.sheets你可以使用字典理解(我认为它更干净,但这取决于你,它产生相同的输出):

writer.sheets = {ws.title: ws for ws in book.worksheets}

so full code will be:所以完整的代码将是:

import pandas
from openpyxl import load_workbook

book = load_workbook('test.xlsx')
writer = pandas.ExcelWriter('test.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = {ws.title: ws for ws in book.worksheets}

for sheetname in writer.sheets:
    df1.to_excel(writer,sheet_name=sheetname, startrow=writer.sheets[sheetname].max_row, index = False,header= False)

writer.save()

You can use the append_df_to_excel() helper function, which is defined in this answer :您可以使用append_df_to_excel()辅助函数,该函数在此答案中定义

Usage examples:用法示例:

filename = r'C:\OCC.xlsx'

append_df_to_excel(filename, df)

append_df_to_excel(filename, df, header=None, index=False)

append_df_to_excel(filename, df, sheet_name='Sheet2', index=False)

append_df_to_excel(filename, df, sheet_name='Sheet2', index=False, startrow=25)

I tried to read an excel, put it in a dataframe and then concat the dataframe from excel with the desired dataframe.我尝试读取 excel,将其放入数据框中,然后将 excel 中的数据框与所需的数据框连接起来。 It worked for me.它对我有用。

def append_df_to_excel(df, excel_path):
    df_excel = pd.read_excel(excel_path)
    result = pd.concat([df_excel, df], ignore_index=True)
    result.to_excel(excel_path, index=False)

df = pd.DataFrame({"a":[11,22,33], "b":[55,66,77]})
append_df_to_excel(df, r"<path_to_dir>\<out_name>.xlsx")

All examples here are quite complicated.这里的所有例子都非常复杂。 In the documentation , it is much easier:文档中,它更容易:

def append_to_excel(fpath, df, sheet_name):
    with pd.ExcelWriter(fpath, mode="a") as f:
        df.to_excel(f, sheet_name=sheet_name)

append_to_excel(<your_excel_path>, <new_df>, <new_sheet_name>)

If someone need it, I found an easier way:如果有人需要它,我找到了一个更简单的方法:

Convert DF to rows in a list将 DF 转换为列表中的行
rows = your_df.values.tolist()
load your workbook加载您的工作簿
workbook = load_workbook(filename=your_excel)
Pick your sheet选择你的工作表
sheet = workbook[your_sheet]
Iterate over rows to append each:迭代行以附加每一行:
for row in rows:
    sheet.append(row)
Save woorkbook when done完成后保存工作簿
workbook.save(filename=your_excel)
Putting it all together:把它们放在一起:
rows = your_df.values.tolist()
workbook = load_workbook(filename=your_excel)
sheet = workbook[your_sheet]
for row in rows:
    sheet.append(row)
workbook.save(filename=your_excel)
def append_to_excel(fpath, df):
 if (os.path.exists(fpath)):
    x=pd.read_excel(fpath)
 else :
    x=pd.DataFrame()

 dfNew=pd.concat([df,x])
 dfNew.to_excel(fpath,index=False)

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

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