Putting many python pandas dataframes to one excel worksheet

后端 未结 4 496
感情败类
感情败类 2020-12-04 07:09

It is quite easy to add many pandas dataframes into excel work book as long as it is different worksheets. But, it is somewhat tricky to get many dataframes into one workshe

4条回答
  •  悲&欢浪女
    2020-12-04 07:17

    user3817518: "Please also share if there is another way to put many dataframes into excel using the built-in df.to_excel functionality !!"

    Here's my attempt:

    Easy way to put together a lot of dataframes on just one sheet or across multiple tabs. Let me know if this works!

    -- To test, just run the sample dataframes and the second and third portion of code.

    Sample dataframes

    import pandas as pd
    import numpy as np
    
    # Sample dataframes    
    randn = np.random.randn
    df = pd.DataFrame(randn(15, 20))
    df1 = pd.DataFrame(randn(10, 5))
    df2 = pd.DataFrame(randn(5, 10))
    

    Put multiple dataframes into one xlsx sheet

    # funtion
    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)   
            row = row + len(dataframe.index) + spaces + 1
        writer.save()
    
    # list of dataframes
    dfs = [df,df1,df2]
    
    # run function
    multiple_dfs(dfs, 'Validation', 'test1.xlsx', 1)
    

    Put multiple dataframes across separate tabs/sheets

    # function
    def dfs_tabs(df_list, sheet_list, file_name):
        writer = pd.ExcelWriter(file_name,engine='xlsxwriter')   
        for dataframe, sheet in zip(df_list, sheet_list):
            dataframe.to_excel(writer, sheet_name=sheet, startrow=0 , startcol=0)   
        writer.save()
    
    # list of dataframes and sheet names
    dfs = [df, df1, df2]
    sheets = ['df','df1','df2']    
    
    # run function
    dfs_tabs(dfs, sheets, 'multi-test.xlsx')
    

提交回复
热议问题