'Python Stargazer LaTeX output unusable

I'm trying to use Python's Stargazer package to output regression tables. However, the output is hopelessly scrambled for someone who doesn't know how to format it.

The default example given:


import pandas as pd
from sklearn import datasets
import statsmodels.api as sm
from stargazer.stargazer import Stargazer

diabetes = datasets.load_diabetes()
df = pd.DataFrame(diabetes.data)
df.columns = ['Age', 'Sex', 'BMI', 'ABP', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6']
df['target'] = diabetes.target

est = sm.OLS(endog=df['target'], exog=sm.add_constant(df[df.columns[0:4]])).fit()
est2 = sm.OLS(endog=df['target'], exog=sm.add_constant(df[df.columns[0:6]])).fit()


stargazer = Stargazer([est])
stargazer.render_latex()


This gives:

'\\begin{table}[!htbp] \\centering\n\\begin{tabular}{@{\\extracolsep{5pt}}lc}\n\\\\[-1.8ex]\\hline\n\\hline \\\\[-1.8ex]\n& \\multicolumn{1}{c}{\\textit{Dependent variable:}} \\\n\\cr \\cline{1-2}\n\\\\[-1.8ex] & (1) \\\\\n\\hline \\\\[-1.8ex]\n ABP & 416.674$^{***}$ \\\\\n & (69.495) \\\\\n Age & 37.241$^{}$ \\\\\n & (64.117) \\\\\n BMI & 787.179$^{***}$ \\\\\n & (65.424) \\\\\n Sex & -106.578$^{*}$ \\\\\n & (62.125) \\\\\n const & 152.133$^{***}$ \\\\\n & (2.853) \\\\\n\\hline \\\\[-1.8ex]\n Observations & 442 \\\\\n $R^2$ & 0.400 \\\\\n Adjusted $R^2$ & 0.395 \\\\\n Residual Std. Error & 59.976(df = 437) \\\\\n F Statistic & 72.913$^{***}$ (df = 4.0; 437.0) \\\\\n\\hline\n\\hline \\\\[-1.8ex]\n\\textit{Note:} & \\multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\\\\n\\end{tabular}\n\\end{table}'

I'm using Stargazer in the first place because I don't know LaTeX, but I can't set this correct for the same reason. Is there a way to have Stargazer output something usable?

As well, what's the quickest way learn how to code together regression tables in LaTeX on one's own? I'd prefer to learn so I can do it myself.

Thank you.



Solution 1:[1]

Using print around it should return a usable Latex code:

     print(stargazer.render_latex())

Solution 2:[2]

You could also save the output directory to a tex file and then include that tex file in a master file (such as a document containing your article or all your tables).

In Python:

file_name = "test.tex" #Include directory path if needed
tex_file = open( file_name, "w" ) #This will overwrite an existing file
tex_file.write( stargazer.render_latex() )
tex_file.close()

In a LaTex file of the same directory as test.tex:

\input{test.tex}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kristina
Solution 2 Leo