close

How to extract the regression coefficient from statsmodels.api?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to extract the regression coefficient from statsmodels.api in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to extract the regression coefficient from statsmodels.api?

  1. How to extract the regression coefficient from statsmodels.api?

    Cribbing from this answer Converting statsmodels summary object to Pandas Dataframe, it seems that the result.summary() is a set of tables

  2. extract the regression coefficient from statsmodels.api

    Cribbing from this answer Converting statsmodels summary object to Pandas Dataframe, it seems that the result.summary() is a set of tables

Method 1

You can use the params property of a fitted model to get the coefficients.

For example, the following code:

import statsmodels.api as sm
import numpy as np
np.random.seed(1)
X = sm.add_constant(np.arange(100))
y = np.dot(X, [1,2]) + np.random.normal(size=100)
result = sm.OLS(y, X).fit()
print(result.params)

will print you a numpy array [ 0.89516052 2.00334187] – estimates of intercept and slope respectively.

If you want more information, you can use the object result.summary() that contains 3 detailed tables with model description.

Method 2

Cribbing from this answer Converting statsmodels summary object to Pandas Dataframe, it seems that the result.summary() is a set of tables, which you can export as html and then use Pandas to convert to a dataframe, which will allow you to directly index the values you want.

So, for your case (putting the answer from the above link into one line):

df = pd.read_html(result.summary().tables[1].as_html(),header=0,index_col=0)[0]

And then

a=df['coef'].values[1]
c=df['coef'].values[0]

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read