我正在使用olsinstatsmodels来运行回归。一旦我对数据帧的每一行运行回归,我想从patsy这些回归中使用的变量中检索 X 变量。但是,我收到一个我似乎无法理解的错误。编辑:我正在尝试运行此处答案中所示的回归,但希望在数据帧的分组版本的每一行上运行回归df,其中它按Date, bal, dist, pay_hist, inc,分组bckts。因此,我首先如上所述对这些数据进行分组,然后尝试对按以下df分组的每一行运行回归Date:df.groupby(['Date']).apply(ols_coef,'bal ~ C(dist) + C(pay_hist) + C(inc) + C(bckts)')我的代码如下:from statsmodels.formula.api import olsdf = df.groupby([['Date','bal', 'dist', 'pay_hist', 'inc', 'bckts']])######run regressiondef ols_coef(x,formula): return ols(formula,data=x).fit().paramsgamma = df.groupby(['Date']).apply(ols_coef,'bal ~ C(dist) + C(pay_hist) + C(inc) + C(bckts)')print('gamme is {}'.format(gamma))#############################Now trying to retrieve the X variables in the regressions aboveformula = 'bal ~ C(dist) + C(pay_hist) + C(inc) + C(bckts)'data = df.groupby(['Date'])[['bckts', 'wac_dist', 'pay_hist', 'inc', 'bal']]y,X = patsy.dmatrices(formula,data,return_type='dataframe')################我收到以下错误,并且不确定如何解决它:patsy.PatsyError: Error evaluating factor: Exception: Column(s) ['bckts', 'dist', 'pay_hist', 'inc', 'bal'] already selected bal ~ C(dist) + C(pay_hist) + C(inc) + C(bckts) ^^^^^^^^^^^
1 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
问题是您将分组数据帧传递到函数中pasty.dmatrices。由于分组数据帧是可迭代的,因此您可以在这样的循环中执行此操作,并将所有 X 数据帧(每组一个)存储到字典中:
import statsmodels.api as sm
import statsmodels.formula.api as smf
import numpy as np
import pandas as pd
import patsy
# Loading data
df = sm.datasets.get_rdataset("Guerry", "HistData").data
# Extracting Independent variables
formula = 'Suicides ~ Crime_parents + Infanticide'
data = df.groupby(['Region'])[['Suicides', 'Crime_parents', 'Infanticide', 'Region']]
X = {}
for name, group in data:
Y, X[name] = patsy.dmatrices(formula, group, return_type='dataframe')
print(X)
添加回答
举报
0/150
提交
取消