Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将使用匹配的列附加到现有excel_Python_Excel_Pandas - Fatal编程技术网

Python将使用匹配的列附加到现有excel

Python将使用匹配的列附加到现有excel,python,excel,pandas,Python,Excel,Pandas,我试图将数据框附加到现有excel文件中。下面的代码检查文件是否存在并附加它。但问题是,如果我的文件中少了一列,它就无法将内容与正确的列匹配。在附加数据框之前,如何让pandas检查现有列名并将其与数据框匹配 if os.path.isfile(output_file): book = load_workbook(output_file) writer = pd.ExcelWriter(output_file, engine='openpyxl', mode='a')

我试图将数据框附加到现有excel文件中。下面的代码检查文件是否存在并附加它。但问题是,如果我的文件中少了一列,它就无法将内容与正确的列匹配。在附加数据框之前,如何让pandas检查现有列名并将其与数据框匹配

    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列)


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

假设您的dataframe如下所示:

A  B  D
0  1  2  3
1  1  2  3
2  1  2  3
excel文件(称为filetoupdate)如下所示:

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

然后,以下代码将生成:

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文件