【问题标题】:Python pandas: how to unpack the statsmodel results and create a column in group by dataframePython pandas:如何解压 statsmodel 结果并按数据框分组创建列
【发布时间】:2020-02-20 07:01:36
【问题描述】:

我正在尝试按组运行线性回归并将结果添加到数据框中的新列中。 这就是我想要做的。

df2 = pd.DataFrame.from_dict({'case': ['foo', 'foo', 'foo', 'bar', 'bar'],
                                 'cluster': [1, 1, 1, 1, 1],
                                 'conf': [1, 2, 3, 1, 4],
                                'conf_1': [11, 12, 13, 11, 14]}) 

def ols_res(df, xcols,  ycol):
    results =  sm.OLS(df[ycol], sm.add_constant(df[xcols])).fit()
    return results.get_influence().cooks_distance[0]

df3 = df2.groupby(['case', 'cluster'])

df3.apply(ols_res, xcols='conf', ycol='conf_1')

我得到的输出是:

case  cluster
bar   1                                                 [nan, nan]
foo   1          [0.42857142857143005, 0.09642857142857146, 10....
dtype: object

每个组的结果大小与组中的行数相同。 我需要以下格式的上述输出。有人可以帮帮我吗?

    case    cluster conf    conf_1   result
0   foo      1       1       11      0.42857142857143005
1   foo      1       2       12      0.09642857142857146
2   foo      1       3       13      10....
4   bar      1       1       11      nan
5   bar      1       4       14      nan

【问题讨论】:

    标签: group-by apply


    【解决方案1】:

    以下对我有用。

    def ols_res_mod(df, xcols,  ycol):
        results =  sm.OLS(df[ycol], sm.add_constant(df[xcols])).fit()
        results.get_influence().cooks_distance[0]
        print(df)
        df['distance'] = results.get_influence().cooks_distance[0]
        return df
    

    不确定,这是否是一种有效的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 2019-01-22
      • 2020-12-20
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多