Using pred () for statsmodels.formula data with different column names using Python and Pandas

I have some regression results from the launch statsmodels.formula.api.ols. Here is an example of a toy:

import pandas as pd
import numpy as np
import statsmodels.formula.api as smf

example_df = pd.DataFrame(np.random.randn(10, 3))
example_df.columns = ["a", "b", "c"]
fit = smf.ols('a ~ b', example_df).fit()

I would like to apply the model to a column c, but a naive attempt to do this does not work:

fit.predict(example_df["c"])

Here is the exception I get:

PatsyError: Error evaluating factor: NameError: name 'b' is not defined
    a ~ b
        ^

I can do something rude and create a new, temporary DataFrameone in which I renamed the column of interest:

example_df2 = pd.DataFrame(example_df["c"])
example_df2.columns = ["b"]
fit.predict(example_df2)

Is there a cleaner way to do this? (not until switching to statsmodels.apiinstead statsmodels.formula.api)

+4
source share
2 answers

You can use the dictionary:

>>> fit.predict({"b": example_df["c"]})
array([ 0.84770672, -0.35968269,  1.19592387, -0.77487812, -0.98805215,
        0.90584753, -0.15258093,  1.53721494, -0.26973941,  1.23996892])

numpy , , :

>>> fit.predict(sm.add_constant(example_df["c"].values), transform=False)
array([ 0.84770672, -0.35968269,  1.19592387, -0.77487812, -0.98805215,
        0.90584753, -0.15258093,  1.53721494, -0.26973941,  1.23996892])
+3

fit :

fit = smf.ols('example_df.a ~ example_df.b', example_df).fit()

.

fit.predict(example_df["c"])

array([-0.52664491, -0.53174346, -0.52172484, -0.52819856, -0.5253607 ,
       -0.52391618, -0.52800043, -0.53350634, -0.52362988, -0.52520823])
+1

All Articles