简体   繁体   中英

Join multiple excel files into one excel file via python

I need to combine all the excel files in my directory into one excel file. for example, I've 3 excel files:

file1:

在此处输入图片说明

file 2:

在此处输入图片说明

file 3:

在此处输入图片说明

I need to concatenate them and get an output as follows

在此处输入图片说明

but instead, they were appended one after another this is my code :

import pandas as pd
import numpy as np
import glob

all_data = pd.DataFrame()
for f in glob.glob('C:/Users/test-results/FinalResult/05-01-2019/*.xlsx'):
   df = pd.read_excel(f)
   all_data = all_data.append(df, ignore_index=True)

writer = pd.ExcelWriter('mycollected_data.xlsx', engine='xlsxwriter')
all_data.to_excel(writer, sheet_name='Sheet1')
writer.save()

during my quest, all I found was how to append dfs,as shown in my code and I didn't figure out how too use join

尝试这个:

all_data = pd.concat([all_data,df],axis=1)

You could use

files = glob.glob('C:/Users/test-results/FinalResult/05-01-2019/*.xlsx')
dfs = (pd.read_excel(f, index_col=0) for f in files)
all_data = pd.concat(dfs, axis=1)
all_data = all_data.merge(df, on = ['first_column_name'], how = 'left')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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