我有3个不同的数据集,我想在同一个excel文件下的3个不同的表格中存储。我尝试如下。有没有紧凑的方法来降低编程复杂性?
{{1}}
答案 0 :(得分:1)
您可以使用pandas(python数据分析库)完成此任务。
通过pip install pandas
安装。
import pandas as pd
datasets = [dataset, column_sum, row_sum]
sheet_names = ['img_reshape', 'column_sum', 'row_sum']
excel_filename = 'abcd.xlsx'
with pd.ExcelWriter(excel_filename) as writer:
for data, sheet in zip(datasets, sheet_names):
df = pd.DataFrame(data)
df.to_excel(writer, sheet_name=sheet, header=None)
答案 1 :(得分:1)
有一种更简单的方法。 xlsxwriter文档中提供了一个示例(链接here) 我在下面发布了一个相当简单的例子。我还添加了三个示例数据帧,以便任何人都可以复制此示例。此外,还有一些可选的参数可以与您感兴趣的dataframe.to_excel一起使用,这些参数在Pandas文档中有概述。 (链接here)。
import pandas as pd
df_1 = pd.DataFrame({'Data_1': [10, 20, 30, ]})
df_2 = pd.DataFrame({'Data_2': [20, 30, 40]})
df_3 = pd.DataFrame({'Data_3': [30, 40, 50]})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('abcd.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df_1.to_excel(writer, sheet_name='img_reshape')
df_2.to_excel(writer, sheet_name='column_sum')
df_3.to_excel(writer, sheet_name='row_sum')
writer.save()
答案 2 :(得分:1)
我也推荐Pandas,但如果你只想用XlsxWriter做,那么你可以这样做:
import xlsxwriter
# Some sample data.
dataset = [[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34]]
column_sum = dataset
row_sum = dataset
xbook = xlsxwriter.Workbook('abcd.xlsx')
xsheet1 = xbook.add_worksheet('img_reshape')
xsheet2 = xbook.add_worksheet('column_sum')
xsheet3 = xbook.add_worksheet('row_sum')
mappings = [(dataset, xsheet1),
(column_sum, xsheet2),
(row_sum, xsheet3)]
for dataset, worksheet in mappings:
for row_num, row_data in enumerate(dataset):
for col_num, cell_data in enumerate(row_data):
worksheet.write(row_num, col_num, cell_data)
xbook.close()
或者对于内循环,你可以这样做:
# Write the data.
for dataset, worksheet in mappings:
for row_num, row_data in enumerate(dataset):
worksheet.write_row(row_num, 0, row_data)