繁体   English   中英

Python Pandas Append 到现有的 excel 与匹配的列

[英]Python Pandas Append to existing excel with matched columns

我正在尝试将 append 和 dataframe 转换为现有的 excel 文件。 下面的代码检查文件是否存在并附加它。 但问题是,如果我的文件中少了一列,则无法将内容与右列匹配。 如何让 pandas 检查现有的列名并将其与我的 dataframe 匹配,然后再附加它?

    if os.path.isfile(output_file):
    book = load_workbook(output_file)
    writer = pd.ExcelWriter(output_file, engine='openpyxl', mode='a')
    writer.book = book
    writer.sheets = {ws.title: ws for ws in book.worksheets}

    for sheetname in writer.sheets:
        source_df.to_excel(writer,
            sheet_name=sheetname, 
            startrow=writer.sheets[sheetname].max_row, 
            columns= ['A','B','D'],
            index = False,
            header= False)

    writer.save()
else:
    source_df.to_excel(output_file, index=False)

现有 Excel:

A B C D
1 2 3 4
5 6 7 8

我的数据框:

A B D
1 2 3

我想要的是:

A B C D
1 2 3 4
5 6 7 8
1 2   3

我得到了什么(它将 D 列写入 C 列)

A B C D
1 2 3 4
5 6 7 8
1 2 3

您的方法的一个可能替代方法是执行以下操作:

假设您的 dataframe 看起来像这样:

A  B  D
0  1  2  3
1  1  2  3
2  1  2  3

并且您的 excel 文件(称为 filetoupdate)看起来像这样:

在此处输入图像描述

然后将产生以下代码:

df_append=pd.read_csv(r"C:\users\k_sego\df2.csv", sep=";" )

to_update = {"shee": df_append}  #I called the sheet 'shee'

file_name = r"C:\....\filetoupdate.xlsx"
excel_reader = pd.ExcelFile(file_name)
excel_writer = pd.ExcelWriter(file_name)

for sheet in excel_reader.sheet_names:
    sheet_df = excel_reader.parse(sheet)
    append_df = to_update.get(sheet)

    if append_df is not None:
        sheet_df = pd.concat([sheet_df, append_df], axis=0)

    sheet_df.to_excel(excel_writer, sheet, index=False)

excel_writer.save()

这个excel文件

在此处输入图像描述

暂无
暂无

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

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