2016-11-14 2073 views
2

我正在创建使用Pandas DataFrame的Python生成报告。目前我正在使用DataFrame.to_string()方法。但是,这会以字符串形式写入文件。有一种方法可以让我在保持表格形式的同时实现此目的,以便使用表格格式。将Python Pandas DataFrame写入Word文档

代码:

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... 
+0

它可能会更容易将数据写入到.csv,然后复制/粘贴或从Excel导入表到Word –

+0

为单一的表是的,我会同意。但是,我正在循环大约12个URL,每个循环约有6个DataFrame。我真的不想为72个表创建一个.csv。 – spriore

+0

您可以添加一些附加信息。你是否试图在MSWord中将数据框写为格式化的表格,或者只是使用'.to_string'方法将格式化的文本添加到行中? – James

回答

6

您可以使用python-docx库编写表直入一个.docx文件。

如果您使用的是康达或使用蟒蛇安装Python,您可以运行命令行命令:

conda install python-docx --channel conda-forge 

或者到点子命令行安装:

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') 
+0

什么是'df = pd.DataFrame(数据)中的数据' ' – pyd

+0

@pyd'data'是数据源(您输入的内容是什么)为您的'DataFrame' – spriore

+0

有没有办法在表?代码可以工作,但我认为我的报告看起来会更好一些,我的熊猫数据框的边界被写入我的Word文档。谢谢! :) – HenryHub