admin管理员组文章数量:1396739
I am making a lot of regression models in Python. I want to report the results in tables in a word-file. Is there any way I can export the results into nicely formatted tables in word, e.g., into a .docx-file?
stargazer
offers great oppurtunities for customizing the tables which I need. It can export into LateX or html - but this is not what I need.
The best solution I can come up with now is to export into html using, then copy-paste into word, but that still requires doing some final modifcations to the tables when they are pasted into Word. And I want to automate as much of the process as possible, since I have MANY tables.
Can I create the tables in a Microsoft Word Document using only code?
import statsmodels.api as sm
import numpy as np
import pandas as pd
np.random.seed(123)
data = pd.DataFrame({
'X1': np.random.randn(100),
'X2': np.random.randn(100),
'Y': np.random.randint(0, 2, 100)
})
model = sm.Logit(data['Y'], sm.add_constant(data[['X1', 'X2']])).fit()
I am making a lot of regression models in Python. I want to report the results in tables in a word-file. Is there any way I can export the results into nicely formatted tables in word, e.g., into a .docx-file?
stargazer
offers great oppurtunities for customizing the tables which I need. It can export into LateX or html - but this is not what I need.
The best solution I can come up with now is to export into html using, then copy-paste into word, but that still requires doing some final modifcations to the tables when they are pasted into Word. And I want to automate as much of the process as possible, since I have MANY tables.
Can I create the tables in a Microsoft Word Document using only code?
import statsmodels.api as sm
import numpy as np
import pandas as pd
np.random.seed(123)
data = pd.DataFrame({
'X1': np.random.randn(100),
'X2': np.random.randn(100),
'Y': np.random.randint(0, 2, 100)
})
model = sm.Logit(data['Y'], sm.add_constant(data[['X1', 'X2']])).fit()
Share
Improve this question
asked Mar 26 at 13:06
EmilAEmilA
1697 bronze badges
1 Answer
Reset to default 1Yes, you could export data to word doc. Here is the code:
import statsmodels.api as sm
import numpy as np
import pandas as pd
from docx import Document
np.random.seed(123)
data = pd.DataFrame({
'X1': np.random.randn(100),
'X2': np.random.randn(100),
'Y': np.random.randint(0, 2, 100)
})
model = sm.Logit(data['Y'], sm.add_constant(data[['X1', 'X2']])).fit()
summary = model.summary2().tables[1]
doc = Document()
doc.add_heading('Regression Results', level=1)
table = doc.add_table(rows=summary.shape[0] + 1, cols=summary.shape[1])
table.style = 'Table Grid'
for j, col_name in enumerate(summary.columns):
table.cell(0, j).text = col_name
for i in range(summary.shape[0]):
for j in range(summary.shape[1]):
table.cell(i + 1, j).text = str(round(summary.iloc[i, j], 4))
doc.save("Regression_Results.docx")
print("Regression table successfully exported to 'Regression_Results.docx'")
With more control on table including table border:
import statsmodels.api as sm
import numpy as np
import pandas as pd
from docx import Document
from docx.shared import Pt, RGBColor
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
np.random.seed(123)
data = pd.DataFrame({
'X1': np.random.randn(100),
'X2': np.random.randn(100),
'Y': np.random.randint(0, 2, 100)
})
model1 = sm.Logit(data['Y'], sm.add_constant(data[['X1', 'X2']])).fit()
model2 = sm.Logit(data['Y'], sm.add_constant(data[['X1']])).fit()
def extract_results(model):
coefs = model.params
std_errs = model.bse
return pd.DataFrame({
'Coefficient': coefs,
'Std. Error': std_errs
})
results1 = extract_results(model1)
results2 = extract_results(model2)
combined_results = pd.concat([results1, results2], axis=1)
combined_results.columns = ['Coef (Model 1)', 'Std. Error (Model 1)', 'Coef (Model 2)', 'Std. Error (Model 2)']
doc = Document()
doc.add_heading('Regression Results', level=1)
table = doc.add_table(rows=combined_results.shape[0] + 1, cols=combined_results.shape[1])
table.style = 'Table Grid'
for j, col_name in enumerate(combined_results.columns):
table.cell(0, j).text = col_name
for i in range(combined_results.shape[0]):
for j in range(combined_results.shape[1]):
table.cell(i + 1, j).text = f"{round(combined_results.iloc[i, j], 4)}"
def set_table_borders(table, color="0000FF", size="4"):
tbl = table._tbl
tblPr = tbl.tblPr
tblBorders = OxmlElement('w:tblBorders')
for border_name in ['top', 'left', 'bottom', 'right', 'insideH', 'insideV']:
border = OxmlElement(f'w:{border_name}')
border.set(qn('w:val'), 'single')
border.set(qn('w:sz'), size)
border.set(qn('w:color'), color)
tblBorders.append(border)
tblPr.append(tblBorders)
set_table_borders(table, color="0000FF", size="8")
doc.save("Regression_Results_Blue_Borders.docx")
print("Regression table with blue borders exported successfully!")
With more control and without table border:
import statsmodels.api as sm
import numpy as np
import pandas as pd
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
np.random.seed(123)
data = pd.DataFrame({
'X1': np.random.randn(100),
'X2': np.random.randn(100),
'Y': np.random.randint(0, 2, 100)
})
model1 = sm.Logit(data['Y'], sm.add_constant(data[['X1', 'X2']])).fit()
model2 = sm.Logit(data['Y'], sm.add_constant(data[['X1']])).fit()
def extract_results(model):
return pd.DataFrame({
'Coefficient': model.params,
'Std. Error': model.bse
})
results1 = extract_results(model1)
results2 = extract_results(model2)
combined_results = pd.concat([results1, results2], axis=1)
combined_results.columns = ['Coef (Model 1)', 'Std. Error (Model 1)', 'Coef (Model 2)', 'Std. Error (Model 2)']
doc = Document()
doc.add_heading('Regression Results', level=1)
table = doc.add_table(rows=combined_results.shape[0] + 1, cols=combined_results.shape[1])
table.style = 'Table Grid'
for j, col_name in enumerate(combined_results.columns):
table.cell(0, j).text = col_name
for i in range(combined_results.shape[0]):
for j in range(combined_results.shape[1]):
table.cell(i + 1, j).text = f"{round(combined_results.iloc[i, j], 4)}"
def remove_table_borders(table):
tbl = table._tbl
tblPr = tbl.tblPr
tblBorders = tblPr.first_child_found_in("w:tblBorders")
if tblBorders is None:
tblBorders = OxmlElement('w:tblBorders')
tblPr.append(tblBorders)
for border_name in ['top', 'left', 'bottom', 'right', 'insideH', 'insideV']:
border = OxmlElement(f'w:{border_name}')
border.set(qn('w:val'), 'none')
border.set(qn('w:sz'), '0')
border.set(qn('w:space'), '0')
border.set(qn('w:color'), 'auto')
tblBorders.append(border)
remove_table_borders(table)
doc.save("Regression_Results_No_Borders.docx")
print("Regression table with NO borders exported successfully!")
本文标签: pythonExporting regression tables from statsmodels into WordStack Overflow
版权声明:本文标题:python - Exporting regression tables from statsmodels into Word - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744142755a2592692.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论