You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:如何按行输出Pandas DataFrame内容到docx并排版

问题:Pandas数据导出到Docx时,无法每行重复显示指定标题

你提到自己是Python新手,正在尝试从Pandas DataFrame中提取数据拼接为字符串后输出到docx文件,但遇到了格式不符合预期的问题。

你的当前代码

add_run("Placeholder A").italic= True
for i in range(0, list(df.shape)[0]):
    A = df.iloc[findings][0]
    B = df.iloc[findings][1]
    C =df.iloc[findings][2]
    output = ('The value of A: {}, B: {}, C: {}').format(A,B,C)
    doc.add_paragraph(output)

期望的输出格式

Placeholder A
print output for row 1 of DF
Placeholder A
print output for row 2 of DF

但目前所有DataFrame的输出内容都显示在同一个Placeholder A下方,接下来我们分析问题所在并给出解决方案:


问题根源

  1. 标题只生成了一次:你把创建Placeholder A的代码写在了循环外面,整个循环过程中只会生成这一个标题段落,后续所有数据段落都会追加在它后面,自然无法实现每行数据前都有标题的效果。
  2. 循环未正确遍历行:循环变量是i,但你在iloc里用了findings作为行索引,这会导致每次循环都提取同一行的数据,而不是遍历DataFrame的每一行。
  3. 冗余写法:list(df.shape)[0]可以简化为df.shape[0],或者更直观的len(df)。

修正后的代码

把生成Placeholder A的逻辑放到循环内部,同时修正行索引的问题:

for i in range(len(df)):
    # 先创建Placeholder A的斜体段落
    title_para = doc.add_paragraph()
    title_para.add_run("Placeholder A").italic = True
    # 提取当前行的A、B、C值
    A = df.iloc[i][0]
    B = df.iloc[i][1]
    C = df.iloc[i][2]
    # 拼接字符串并添加数据段落
    output = f'The value of A: {A}, B: {B}, C: {C}'
    doc.add_paragraph(output)

额外优化建议

如果你的DataFrame有明确的列名(比如列名为"A"、"B"、"C"),可以用iterrows()遍历行,通过列名取值,代码可读性会更好:

for idx, row in df.iterrows():
    # 生成标题段落
    title_para = doc.add_paragraph()
    title_para.add_run("Placeholder A").italic = True
    # 通过列名提取值并拼接
    output = f'The value of A: {row["A"]}, B: {row["B"]}, C: {row["C"]}'
    doc.add_paragraph(output)

这样修改后,就能完美实现你想要的输出格式了。


内容的提问来源于stack exchange,提问作者user11464178

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:25:10