带有statsmodels的sm.OLS.from_formula('variable1〜variable2 + x')问题

时间:2019-07-19 19:52:04

标签: python-3.x pandas statsmodels

如果我运行函数advanced_stats(['one', 'two', 'three'], 'myFile.csv')[0].summary()advanced_stats(['one', 'two', 'three'], 'myFile.csv')[0].pvalues,则下面的函数将输出file[independent]file[dependent]而不是实际名称'one', 'two' or 'three'  输出值时,我需要知道列名。计算和代码可以完美地工作,但是标签很重要,因为我将它们用作数据框的一部分。因此,我需要知道如何输出标题“ one”而不是file[dependent]

def advanced_stats(categories, file):

    finalData = []
    for dependent in categories:
        for independent in categories:
            if dependent == independent:
                pass
            else:
                model = sm.OLS.from_formula('file[dependent] ~ file[independent] + age + sex + height', file).fit()
                finalData.append(model)

    return finalData

2 个答案:

答案 0 :(得分:1)

model = sm.OLS.from_formula('file[dependent] ~ file[independent] + age + sex + height', file)
model.exog_names[:] = [dependent if x=='file[dependent]' else x for x in model.exog_names]
model.exog_names[:] = [independent if x=='file[independent]' else x for x in model.exog_names]
result = model.fit()
finalData.append(result)

答案 1 :(得分:0)

使用python的字符串格式,我发现以下是不需要exog_names以及更多for循环的最佳解决方案。

model = sm.OLS.from_formula('{} ~ {} + age + sex + height'.format(dependent, independent), file)