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)
不,这在帕西还不存在,不幸的是。看这个issue。
由于这仍然没有包含在
patsy
中,所以我编写了一个小函数,当我需要对所有列运行statsmodels
模型时,我会调用它(可以选择例外情况)例如,对于名为
df
、列为y, x1, x2, x3
的数据帧,运行ols_formula(df, 'y', 'x3')
将返回'y ~ x1 + x2'
我在patsy文档中也没有找到
.
等价物。但它在简洁性方面的不足,可以通过在Python中提供强大的字符串操作来弥补。因此,可以使用在您的情况下,这将给出
x1+x2+x3
。最后,可以使用y
创建字符串公式,并将其传递给任何拟合过程相关问题 更多 >
编程相关推荐