【问题标题】:Python apply list of coefficient (from regression model) on new dataPython在新数据上应用系数列表(来自回归模型)
【发布时间】:2021-02-02 07:43:38
【问题描述】:

我有一份来自 sklearn 逻辑回归模型的系数列表:

[-0.52  0.31  0.059 0.1 ]

现在,我有一个新的数据框,例如:

    df =  A  B  C  D
          1  5  2  7
          6  2  1  9

我想添加一个新列 - 这是在每一行上应用 coeffs 列表的结果。 所以值将是:

1*-0.52 + 5*0.31 + 2*0.059 + 7*0.1 = 1.848
6*-0.52 + 2*0.31 + 1*0.059 + 9*0.1 = -1.541

最好的方法是什么?

谢谢!

【问题讨论】:

  • df = [1 5 2 7 6 2 1 9] 不是数据框。是列表还是 pd.Series?

标签: python pandas dataframe scikit-learn logistic-regression


【解决方案1】:

所以我们可以做到numpyreshape

l = [-0.52,  0.31,  0.059, 0.1 ]
s = [1, 5 ,2 ,7 ,6 ,2 ,1 ,9]
np.sum(np.array(s).reshape(-1,4)*l, axis=1)
Out[140]: array([ 1.848, -1.541])

更新

df['New'] = df.dot(l)
df
Out[145]: 
   A  B  C  D    New
0  1  5  2  7  1.848
1  6  2  1  9 -1.541

【讨论】:

    【解决方案2】:

    这是矩阵乘法。你可以这样做:

    df['new_col'] = df @ a
    

    输出:

       A  B  C  D  new_col
    0  1  5  2  7    1.848
    1  6  2  1  9   -1.541
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2017-07-19
      • 2023-03-19
      • 1970-01-01
      • 2020-12-22
      • 2020-04-02
      • 2021-06-29
      相关资源
      最近更新 更多