statsmodels线性回归-patsy公式,包括mod中的所有预测因子

2024-05-16 21:12:04 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数据帧(我们称之为DF),其中y是因变量,x1, x2, x3是我的自变量。在R中,我可以使用以下代码来拟合线性模型,.将包括模型中的所有自变量:

# R code for fitting linear model
result = lm(y ~ ., data=DF)

如果不显式地将我的所有自变量添加到公式中,我就无法用patsy公式来计算statsmodels如何做到这一点。patsy与R有等价物吗?我在帕西的文件里找不到它。


Tags: 数据代码模型dfforcode线性公式
3条回答

不,这在帕西还不存在,不幸的是。看这个issue

由于这仍然没有包含在patsy中,所以我编写了一个小函数,当我需要对所有列运行statsmodels模型时,我会调用它(可以选择例外情况)

def ols_formula(df, dependent_var, *excluded_cols):
    '''
    Generates the R style formula for statsmodels (patsy) given
    the dataframe, dependent variable and optional excluded columns
    as strings
    '''
    df_columns = list(df.columns.values)
    df_columns.remove(dependent_var)
    for col in excluded_cols:
        df_columns.remove(col)
    return dependent_var + ' ~ ' + ' + '.join(df_columns)

例如,对于名为df、列为y, x1, x2, x3的数据帧,运行ols_formula(df, 'y', 'x3')将返回'y ~ x1 + x2'

我在patsy文档中也没有找到.等价物。但它在简洁性方面的不足,可以通过在Python中提供强大的字符串操作来弥补。因此,可以使用

all_columns = "+".join(DF.columns - ["y"])

在您的情况下,这将给出x1+x2+x3。最后,可以使用y创建字符串公式,并将其传递给任何拟合过程

my_formula = "y~" + all_columns
result = lm(formula=my_formula, data=DF)

相关问题 更多 >