我试图复制这个解决方案Python pandas: how to run multiple univariate regression by group,但是使用sklearn线性回归而不是statsmodels。你知道吗
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
df = pd.DataFrame({
'y': np.random.randn(20),
'x1': np.random.randn(20),
'x2': np.random.randn(20),
'grp': ['a', 'b'] * 10})
def ols_res(x, y):
return pd.Series(LinearRegression.fit(x,y).predict(x))
results = df.groupby('grp').apply(lambda x : x[['x1', 'x2']].apply(ols_res, y=x['y']))
print(results)
我得到:
TypeError: ("fit() missing 1 required positional argument: 'y'", 'occurred at index x1')
结果应与第一篇链接的文章相同,即:
x1 x2
grp
a 0 -0.102766 -0.205196
1 -0.073282 -0.102290
2 0.023832 0.033228
3 0.059369 -0.017519
4 0.003281 -0.077150
... ...
b 5 0.072874 -0.002919
6 0.180362 0.000502
7 0.005274 0.050313
8 -0.065506 -0.005163
9 0.003419 -0.013829
您的代码有两个小问题:
您没有实例化
LinearRegression
对象,因此您的代码实际上尝试调用LinearRegression
类的未绑定fit
方法。即使修复了此问题,
LinearRegression
实例也将无法执行fit
和transform
,因为它需要一个2D数组,而得到一个1D数组。因此,您还需要重塑每个Series
中包含的数组。输出:
相关问题 更多 >
编程相关推荐