我是Python新手。我正在研究一个大型的分析程序,这是它的一个片段。现在,此代码段导出多个excel文件。是否可以在单个Excel文档中的工作表上保存每个循环所执行的操作?所以基本上现在,它导出5个文件,而不是导出5个单独的文件,我可以使用这个循环导出1个文件,有5个文件吗?
x = 0
y = 0
#these are empty variables for the while loop
#while loop that loops up to the system amount
#breaks up df into systems
#exports excel for each system
while x < int(SystemCount):
x += 1
y += 1
System = minus4[minus4['System'] == "System " + str(y)]
System.to_excel('U4Sys' + str(y) + '.xlsx', sheet_name='sheet1', index=False)
print(System.head())
最后的印刷品打印出来
email System
test1@test.com System 1
test2@test.com System 1
test3@test.com System 1
test4@test.com System 1
test5@test.com System 1
email System
test1@test.com System 2
test2@test.com System 2
test3@test.com System 2
test4@test.com System 2
test5@test.com System 2
email System
test1@test.com System 3
test2@test.com System 3
test3@test.com System 3
test4@test.com System 3
test5@test.com System 3
感谢您抽出宝贵时间阅读本文!
答案 0 :(得分:1)
编辑(使用pandas
和ExcelWriter
来考虑OP):
您需要使用ExcelWriter
定义目标文件,然后使用可变工作表名称对其进行写入。还为迭代提供了一些Python清理:
#breaks up df into systems
#exports excel for each system
writer = ExcelWriter('U4SysOutput.xlsx')
for x in range(1, int(SystemCount)+1):
System = minus4[minus4['System'] == "System " + str(x)]
System.to_excel(writer, sheet_name='sheet{}'.format(x), index=False)
print(System.head())
答案 1 :(得分:0)
您需要在pandas.ExcelWriter()
pandas.to_excel()
以下是您的流程的简化版本:
import numpy as np
import pandas as pd
# Output Excel file:
writer = pd.ExcelWriter("your_excel_filepath.xlsx")
# Your variables:
x, y = 0, 0
# The loop:
while x < 5:
x += 1
y += 1
# The DataFrame for this iteration:
df = pd.DataFrame(np.random.randn(5,4), columns=list("ABCD"))
# Write the DataFrame to a new sheet:
df.to_excel(writer, "sheet_{}".format(x))
writer.save()