如何使用python-docx

问题描述

我正在尝试使用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)

添加了没有索引的表

enter image description here

如何将带有索引的完整DataFrame作为表添加到文档中?

任何建议或参考将不胜感激。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...