如下面的代码所示,我想使用pandas
来收集一些内容并使用to_excel
生成一个excel。
import pandas as pd
import pandas.io.formats.excel
columns = [['2020-04', 'AMZ', 'EC', 'DL'], ['2020-04', 'AMZ', 'EC', 'DRL'], ['2020-04', 'AMZ', 'Fin', 'BFI'],
['2020-04', 'Google', 'GAME', 'BV'], ['2020-04', 'Google', 'GAME', 'DRL'], ['2020-04', 'Google', 'GAME', 'DRL-CN'], ['index_total', '', '', '']]
data = {0: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4684.41], 1: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 2:
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 6680.65], 3: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 14453.25], 4: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 48609.45], 5: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7250.23], 6: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 7: [0.0, 0.0, 0.0, 0.0, 0.0
, 0.0, 1735632.01], 8: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 98941.92], 9: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1939.64]}
indices = {0: ['backend', 'entity 1', 'type_1'],
1: ['backend', 'entity 1', 'type_1'],
2: ['backend', 'entity 12', 'type_2'],
3: ['backend', 'entity 12', 'type_2'],
4: ['backend', 'entity 14', 'type_2'],
5: ['backend', 'entity 15', 'type_2'],
6: ['backend', 'entity 12', 'type_2'],
7: ['frontend', 'entity 1', 'type_23'],
8: ['frontend', 'entity 1', 'type_4'],
9: ['frontend', 'entity 6', 'type_7'],
}
header_indices = ["data_source", "entity", "settle_type"]
indices = pd.MultiIndex.from_tuples(indices.values(), names=header_indices)
columns = pd.MultiIndex.from_tuples(columns)
pandas.io.formats.excel.header_style = None
df = pd.DataFrame(data.values(), index=indices, columns=columns)
print(df)
# to_excel
df.to_excel("demo.xlsx", merge_cells=True)
然后我得到一个像
的数据框 2020-04 ... index_total
AMZ ... Google
EC Fin ... GAME
DL DRL BFI ... DRL DRL-CN
data_source entity settle_type ...
backend entity 1 type_1 0.0 0.0 0.0 ... 0.0 0.0 4684.41
type_1 0.0 0.0 0.0 ... 0.0 0.0 0.00
entity 12 type_2 0.0 0.0 0.0 ... 0.0 0.0 6680.65
type_2 0.0 0.0 0.0 ... 0.0 0.0 14453.25
entity 14 type_2 0.0 0.0 0.0 ... 0.0 0.0 48609.45
entity 15 type_2 0.0 0.0 0.0 ... 0.0 0.0 7250.23
entity 12 type_2 0.0 0.0 0.0 ... 0.0 0.0 0.00
frontend entity 1 type_23 0.0 0.0 0.0 ... 0.0 0.0 1735632.01
type_4 0.0 0.0 0.0 ... 0.0 0.0 98941.92
entity 6 type_7 0.0 0.0 0.0 ... 0.0 0.0 1939.64
如果我直接使用to_excel
将其导出到excel,我会得到
但是我的预期输出是:
如何调整数据框格式以导出预期的excel文件?
谢谢
答案 0 :(得分:1)
为此,您可以使用xlsxwriter
,方法是先将数据帧写入excel,然后合并所需的单元格。由于您正在重置索引,因此您必须手动从excel中删除新索引,因为对于具有多索引列的数据框,to_excel
不支持index=False
。
df.reset_index(inplace=True)
writer = pd.ExcelWriter('demo.xlsx', engine='xlsxwriter')
workbook = writer.book
merge_format = workbook.add_format({
'border': 1,
'align': 'center',
'valign': 'vcenter'})
worksheet = workbook.add_worksheet('Sheet1')
writer.sheets['Sheet1'] = worksheet
df.to_excel(writer, sheet_name='Sheet1')
worksheet.merge_range('B1:B4', df.columns[0][0], merge_format)
worksheet.merge_range('C1:C4', df.columns[1][0], merge_format)
worksheet.merge_range('D1:D4', df.columns[2][0], merge_format)
worksheet.merge_range('K1:K4', df.columns[9][0], merge_format)
writer.save()