问题描述
我正在尝试使用python-docx
将交叉制表数据作为表格添加到Word文档中。
我无法添加包括索引在内的完整表格。
交叉表数据ctab
time Lunch Dinner
day
Thur 0.250000 0.004098
Fri 0.028689 0.049180
Sat 0.000000 0.356557
Sun 0.000000 0.311475
下面是我尝试的代码
df = sns.load_dataset('tips')
# Create an instance for Document
doc = Document()
# Header
doc.add_paragraph("Bivariate Analysis - Cross Tabulation",style='Intense Quote')
unique_lcc = [('day','time'),('day','sex'),('time','smoker'),('sex','time')]
for i in unique_lcc:
ctab = pd.DataFrame((pd.crosstab(df[i[0]],df[i[1]],normalize=True)))
doc.add_paragraph("Cross Tabulation for " + i[0] +" and " + i[1])
# Add table
t = doc.add_table(ctab.shape[0]+1,ctab.shape[1])
t.style = 'Medium Grid 2 Accent 2'
# add the header rows.
for j in range(ctab.shape[-1]):
t.cell(0,j).text = ctab.columns[j]
# add the rest of the data frame
for k in range(ctab.shape[0]):
for j in range(ctab.shape[-1]):
t.cell(k+1,j).text = str(ctab.values[k,j])
d=doc.add_paragraph()
d.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
w=d.add_run(f"""The above table shows a cross tabulation between {i[0]} and {i[1]}.""")
# Save
filename = "output/CrossTabulation_Report.docx"
# save the docx
doc.save(filename)
添加了没有索引的表
如何将带有索引的完整DataFrame作为表添加到文档中?
任何建议或参考将不胜感激。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)