Write multiple pandas dataframes to excel

a 夏天 提交于 2019-12-24 04:31:36

问题


I am attempting to write multiple pandas dataframes which I extracted from a larger dataset into multiple worksheets of an excel workbook. The issue is that it only writes the first dataframe i.e. index[0], so the resulting workbook has only one worksheet, see sheet1 below. What am I missing? This is a recreation of my problem.

Code:

import pandas as pd
from pandas import ExcelWriter

df_list = []
a = pd.DataFrame({'A':[1,2,3,4,5,6,7,8,9], 'B':[10,11,12,13,14,15,16,17,18]})
b = pd.DataFrame({'C':[11,22,33,44,55,66,77,88,99], 'D':[105,117,128,139,140,153,166,176,188]})

df_list.append(a)
df_list.append(b)

writer = ExcelWriter('test_output.xlsx')
for n, df in enumerate(df_list):
    df.to_excel(writer, 'sheet%s' % str(n + 1))
    writer.save()

Sheet1:

    A   B
0   1   10
1   2   11
2   3   12
3   4   13
4   5   14
5   6   15
6   7   16
7   8   17
8   9   18

回答1:


You need to call writer.save() after the for construct.

Once this method is called, the writer object is effectively closed and you will not be able to use it to write more data.

writer = ExcelWriter('test_output.xlsx')
for n, df in enumerate(df_list):
    df.to_excel(writer, 'sheet%s' % str(n + 1))
writer.save()


来源:https://stackoverflow.com/questions/50315010/write-multiple-pandas-dataframes-to-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!