statsmodels summary to latex
Asked Answered
F

1

10

I'm a newbie to latex and I want to import a statsmodels(python-package) summary to my report in latex. I found that it's possible to transform a summary into a latex tabular with the following method: latex_as_tabular. Until now everything is working. Now I have to store the tabular, but I don't really understand how this works.

I suppose I have to use the following commands:

x_values=sm.add_constant(x_values)
model=sm.OLS(y_values, x_values)
results=model.fit()
tbl=results.summary(xname=['b,'a'],yname='y')
with open('c:/temp/temp.tex','w') as fh:
    fh.write( tbl.as_latex_tabular() )

this code doesn't work until now. most of the times the console gives the error: tex-file doesn't exists or not permitted in this map. I don't really understand what I have to do here. Could someone please help me with this ?

Factious answered 3/5, 2015 at 8:10 Comment(2)
Please consider adding the error stacktrace to your question to make it easier for others with a similar problem to find your question.Twit
There's an error in the example code: A ' is missing to close character b. Plus I recommend to code according to PEP8, in particular having spaces around operators.Crosseyed
T
18

That seems to be a misunderstanding. You can either convert a whole summary into latex via summary.as_latex() or convert its tables one by one by calling table.as_latex_tabular() for each table.

The following example code is taken from statsmodels documentation. Note that you cannot call as_latex_tabular on a summary object.

import numpy as np
import statsmodels.api as sm

nsample = 100
x = np.linspace(0, 10, 100)
X = np.column_stack((x, x**2))
beta = np.array([1, 0.1, 10])
e = np.random.normal(size=nsample)

X = sm.add_constant(X)
y = np.dot(X, beta) + e

model = sm.OLS(y, X)
results = model.fit()

# do either
print(results.summary().as_latex())

# alternatively
for table in results.summary().tables:
    print(table.as_latex_tabular())
Twit answered 3/5, 2015 at 10:14 Comment(2)
Ok you're right. But it's still not clear for me how it's possible to insert it into a tex-file. the summery is converted into latex string and after that ?Factious
After that you have a string with latex code - no more, no less. What you do with that string is up to you. You could e.g. write that string into a file and include this file in one of your latex documents.Twit

© 2022 - 2024 — McMap. All rights reserved.