我有一个正在运行的python脚本,当前该脚本执行三项单独的工作,并将每个结果输出到一个不同的excel文件。是否可以将我的所有输出保存在不同工作表的一个excel文件中?看来最新结果总是会覆盖整个excel文件。
以下是我的想法:
df_finit1.to_excel('OutFile.xlsx', sheet_name = 'Sheet1')
df_finit2.to_excel('OutFile.xlsx', sheet_name = 'Sheet2')
df_finit3.to_excel('OutFile.xlsx', sheet_name = 'Sheet3')
我还尝试使用xlsx writer创建具有3个不同工作表的文件,并输出到这些工作表,但结果却相同。有小费吗?
答案 0 :(得分:2)
您必须像这样使用ExcelWriter :(也许您必须安装此模块)
##############################################################################
#
# An example of writing multiple dataframes to worksheets using Pandas and
# XlsxWriter.
import pandas as pd
# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})
df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('result_multiple.xlsx', engine='xlsxwriter')
# Write each dataframe to a different worksheet.
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')
df3.to_excel(writer, sheet_name='Sheet3')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
答案 1 :(得分:2)
您应该使用ExcelWriter
,它可以打开单个.xlsx
文件并进行操作。
import pandas as pd
# Initialize xlsx writer
writer = pd.ExcelWriter('output_file.xlsx', engine='xlsxwriter')
workbook = writer.book
df1 = pd.DataFrame({"a": [1,2,3],
"b": [1,2,3]})
df2 = pd.DataFrame({"c": [1,2,3],
"d": [1,2,3]})
df3 = pd.DataFrame({"e": [1,2,3],
"f": [1,2,3]})
df1.to_excel(writer,
sheet_name="sheet1",
startrow=0,
startcol=0)
df2.to_excel(writer,
sheet_name="sheet2",
startrow=0,
startcol=0)
df3.to_excel(writer,
sheet_name="sheet3",
startrow=0,
startcol=0)
writer.save()