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
Add a comment  | 

1 Answer 1

Reset to default 1

Yes, 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