5

使用此代码,可以在新的工作表迭代数据框列表中导出每个数据框:

def save_xls(list_dfs, xls_path):
    writer = ExcelWriter(xls_path)
    for n, df in enumerate(list_dfs):
        df.to_excel(writer,'sheet_dati%s' % n)
    writer.save()
save_xls(list_dfs, xls_path)

但是可以在一个工作表中导出两个或多个数据框吗?

4

4 回答 4

12

像这样的东西:?

from pandas import ExcelWriter
def dfs2xlsx(list_dfs,xls_path = None):
    #save_xls([df1,df2],'output1.xlsx')
    if xls_path == None :
        xls_path = '~tmp.xlsx'
    writer = ExcelWriter(xls_path)
    i=0
    for n, df in enumerate(list_dfs):
        df.to_excel(writer,'Sheet1',startcol=i,startrow =2)
        i+= len(df.columns) + 2
    writer.save()
    os.system('start excel.exe %s' %(writer.path ))
于 2014-02-17T17:59:31.847 回答
5

如果你想DataFrames在同一张纸上有多个,你会如何组合它们?取而代之的是,预先将它们合并、连接或连接成一个DataFrame,因为 pandas 为您提供了多种方式。然后做你的出口。

于 2013-01-09T13:25:30.103 回答
3

我认为在导出(通过)之前你会更好地执行concat这些 DataFrames 。那是:to_excel

pd.concat(list_dfs).to_excel(xls_path)
于 2013-01-09T13:25:37.263 回答
3

+1 for ashkan's answer. This method allows you to write the headers multiple times, and do things like leaving space between the individual dataframes much more easily than inserting blank rows into one larger concat'd dataframe. For instance:

writer = pd.ExcelWriter(os.path.join(filepath, filename))
for item in list_of_dataframes:
    item.to_excel(writer, "sheetname", startcol=0, startrow=n)
    n += len(item.index) + 2
writer.save()

This allows you to write multiple (possibly different or unrelated) dataframes into one excel sheet, one after another, leaving a blank line between each as you go down the page.

于 2015-12-28T21:46:31.930 回答