text_plain_output_2.png text_plain_output_1.png
import pandas as pd

import statsmodels.formula.api as smf

url = 'https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/swiss.csv'
df = pd.read_csv(url, index_col=0)

df.columns = ['fertility', 'agri', 'exam', 'edu', 'catholic', 'infant_mort']

formula = 'fertility ~ %s' % ' + '.join(df.columns.values[1:])
formula

lin_reg = smf.ols(formula, data=df).fit()
lin_reg.summary()

err_series = lin_reg.params - lin_reg.conf_int()[0]
err_series

coef_df = pd.DataFrame({'coef': lin_reg.params.values[1:], 'err': err_series.values[1:], 'varname': err_series.index.values[1:]})
coef_df

formula_1 = 'fertility ~ %s' % ' + '.join(df.columns.values[1:-1])
mod_1 = smf.ols(formula_1, data=df).fit()
mod_1.params

formula_2 = 'fertility ~ %s' % ' + '.join(df.columns.values[1:-2].tolist() + ['infant_mort'])
mod_2 = smf.ols(formula_2, data=df).fit()
mod_2.params

coef_df = pd.DataFrame()
for i, mod in enumerate([mod_1, mod_2]):
    err_series = mod.params - mod.conf_int()[0]
    coef_df = coef_df.append(pd.DataFrame({'coef': mod.params.values[1:], 'err': err_series.values[1:], 'varname': err_series.index.values[1:], 'model': 'model %d' % (i + 1)}))
coef_df