编写多个 pandas 数据框以表现出色 [英] Write multiple pandas dataframes to excel
问题描述
我正在尝试将多个熊猫dataframes
从更大的数据集中提取到一个Excel工作簿的多个工作表中.问题在于它仅写入第一个数据帧,即index[0]
,因此生成的工作簿只有一个工作表,请参见下面的sheet1
.我想念什么?这是我的问题的重头戏.
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.
代码:
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
推荐答案
您需要在for
构造之后调用writer.save()
.
You need to call writer.save()
after the for
construct.
调用此方法后,writer
对象实际上已关闭,您将无法使用它写入更多数据.
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()
这篇关于编写多个 pandas 数据框以表现出色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!