使用循环将多个数据框从上到下合并到单个工作表中

时间:2018-12-05 18:02:01

标签: python excel pandas xlsxwriter

我的python很初级。我想要做的是获取第一个数据帧,搜索一个唯一编号,并在相同格式的模板中创建一个新的df,使用相同的唯一编号,搜索第二个df,并创建一个与该唯一编号相关的新df以指定的格式,然后将所有循环数据彼此顶部合并。

这是代码

#function
def multiple_dfs(df_list, sheets, file_name, spaces):
writer = pd.ExcelWriter(file_name,engine='xlsxwriter')   
row = 0



for i in uniqueIR:
    dftopi = df_out[df_out['Invoice Reference Number'] == i]
    df2 = df_out_fin[df_out_fin['Invoice Reference Number'] == i]
    df3 = df2.drop(columns = ['Invoice Reference Number'])

    for dataframe in df_list:
        dataframe.to_excel(writer,sheet_name=sheets,startrow=row , startcol=0, index = False)   
        row = row + len(dataframe.index) + spaces  
writer.save()

# list of dataframes
dfs = [dftopi,df3]

# run function
multiple_dfs(dfs, 'Validation', 'test1.xlsx', 1) 

这就是我想要的: table output

1 个答案:

答案 0 :(得分:1)

想出一种解决方案,如果将来有人感到奇怪:

writer = pd.ExcelWriter('test3.xlsx', engine = 'xlsxwriter')

dflist = []
for i in uniqueIR:


    dftopi = df_out[df_out['Invoice Reference Number'] == i]
    df2 = df_out_fin[df_out_fin['Invoice Reference Number'] == i]
    df3 = df2.drop(columns = ['Invoice Reference Number'])

    dftopi.to_excel(writer, sheet_name = 'Top Half' + str(i), index = False)    
    df3.to_excel(writer, sheet_name = 'Bottom Half' + str(i), index = False)

    dflist.append(dftopi)
    dflist.append(df3)
writer.save()


def multiple_dfs(df_list, sheets, file_name, spaces):
    writer = pd.ExcelWriter(file_name,engine='xlsxwriter')   
    row = 0

    for dataframe in df_list:
            dataframe.to_excel(writer,sheet_name=sheets,startrow=row , startcol=0, index = False)   
            row = row + len(dataframe.index) + spaces


    writer.save()

multiple_dfs(dflist, 'Validation', 'test4.xlsx', 1)