python - 将 Python Pandas DataFrame 写入 Word 文档

标签 python pandas dataframe

我正在努力创建一个使用 Pandas DataFrames 的 Python 生成的报告。目前我正在使用 DataFrame.to_string() 方法。但是,这将作为字符串写入文件。有没有一种方法可以让我在将其保留为表格的同时实现这一点,以便我可以使用表格格式。

代码:

SEMorgkeys = client.domain_organic(url, database = "us", display_limit = 10, export_columns=["Ph,Pp,Pd,Nq,Cp,Ur,Tr"])
org_df = pd.DataFrame(SEMorgkeys)

f = open(name, 'w')
f.write("\nOrganic:\n")
f.write(org_df.to_string(index=False,justify="left"))
f.close()

当前打印输出(字符串形式):

CPC    Keyword                        Position Difference Previous Position Search Volume Traffic (%) Url                                               
75.92       small business factoring   0                   1                 210          11.69       https://www..com/small-business-f...
80.19              factoring company   0                   8                1600           5.72       https://www..com/factoring-vs-ban...

最佳答案

您可以使用 python-docx 库将表格直接写入 .docx 文件。

如果您使用的是 Conda 或使用 Anaconda 安装了 Python,则可以从命令行运行命令:

conda install python-docx --channel conda-forge

或者从命令行进行 pip 安装:

pip install python-docx

安装后,我们可以用它打开文件,添加表格,然后用数据框数据填充表格的单元格文本。

import docx
import pandas as pd

# i am not sure how you are getting your data, but you said it is a
# pandas data frame
df = pd.DataFrame(data)

# open an existing document
doc = docx.Document('./test.docx')

# add a table to the end and create a reference variable
# extra row is so we can add the header row
t = doc.add_table(df.shape[0]+1, df.shape[1])

# add the header rows.
for j in range(df.shape[-1]):
    t.cell(0,j).text = df.columns[j]

# add the rest of the data frame
for i in range(df.shape[0]):
    for j in range(df.shape[-1]):
        t.cell(i+1,j).text = str(df.values[i,j])

# save the doc
doc.save('./test.docx')

关于python - 将 Python Pandas DataFrame 写入 Word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40596518/

相关文章:

python - 在导出到 Excel 之前如何命名 DataFrame 中的行和列?

python - Celery v4 没有按预期路由任务

python - 如何使用非orm模型进行自定义分页

python - 为 Pandas 数据框中的时间戳数据设置时区

python - 是否有一种有效/最佳的方法来为 Pandas 数据框列中的值分配分数?

r - 使用函数 rle() 时出错

python - 找到使每个字典在多个字典中唯一的键的最小数量

python - 使用 MySQL 和 Python 返回基于子查询的元组

python - 如何在 Pandas 中组合宽数据框和长数据框?

python - pandas 获取时间戳差异(以毫秒为单位)作为整数