我的输入是一个数据框,我需要将其保存在 Excel 中作为表格。 https://xlsxwriter.readthedocs.io/working_with_tables.html
import pandas as pd
columns = pd.MultiIndex.from_product([['A', 'B'], ['x', 'y', 'z']])
df = pd.DataFrame(np.arange(1, len(columns)*5+1).reshape(-1, len(columns)), index=range(5), columns=columns)
print(df)
A B
x y z x y z
0 1 2 3 4 5 6
1 7 8 9 10 11 12
2 13 14 15 16 17 18
3 19 20 21 22 23 24
4 25 26 27 28 29 30
row = df.shape[0]
col = df.shape[1]
with pd.ExcelWriter('final_template.xlsx', engine='xlsxwriter') as writer:
df.to_excel(writer)
writer.sheets['Sheet1'].add_table(1, 1, row+2, col, {'autofilter': True})
writer.sheets['Sheet1'].autofit()
代码工作正常,除了一件事之外,即不保留列名称。
你能告诉我如何解决这个问题吗?我需要
['x', 'y', 'z'], ...
而不是 ['column1', ...]
。
我的实际 Excel 文件如下所示:
我发现一篇文章解释了如何做到这一点,但使用的示例不是多重索引。 https://xlsxwriter.readthedocs.io/working_with_pandas.html#adding-a-dataframe-to-a-worksheet-table
这是将数据帧标头添加到带有清理标头的表中的基本选项
import numpy as np
import pandas as pd
import re
columns = pd.MultiIndex.from_product([['A', 'B'], ['x', 'y', 'z']])
df = pd.DataFrame(np.arange(1, len(columns) * 5 + 1).reshape(-1, len(columns)), index=range(5), columns=columns)
row = df.shape[0]
col = df.shape[1]
with pd.ExcelWriter('final_template.xlsx', engine='xlsxwriter') as writer:
df.to_excel(writer)
column_headers = [{'header': re.subn("'|\(|\)|,| ", "", str(c))[0]} for c in df.columns]
writer.sheets['Sheet1'].add_table(1, 1, row + 2, col, {'columns': column_headers, 'autofilter': True})
writer.sheets['Sheet1'].autofit()