【发布时间】:2022-07-27 22:40:28
【问题描述】:
我有以下数据框:
import pandas as pd
from sklearn import linear_model
import statsmodels.api as sm
Stock_Market = {\'Year\': [2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2017,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016],
\'Month\': [12, 11,10,9,8,7,6,5,4,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1],
\'Interest_Rate\': [2.75,2.5,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2,2,2,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75,1.75],
\'Unemployment_Rate\': [5.3,5.3,5.3,5.3,5.4,5.6,5.5,5.5,5.5,5.6,5.7,5.9,6,5.9,5.8,6.1,6.2,6.1,6.1,6.1,5.9,6.2,6.2,6.1],
\'Stock_Index_Price\': [1464,1394,1357,1293,1256,1254,1234,1195,1159,1167,1130,1075,1047,965,943,958,971,949,884,866,876,822,704,719]
}
df = pd.DataFrame(Stock_Market,columns=[\'Year\',\'Month\',\'Interest_Rate\',\'Unemployment_Rate\',\'Stock_Index_Price\'])
目前,我可以使用以下函数对 \'Stock_Index_Price\' 执行 \'Interest_Rate\' 和 \'Unemployment_Rate\' 的多元回归:
def perform_regression_multiple(y, x1, x2=\"\"):
test = df[[y, x1, x2]].reset_index(drop=True)
X = test[[x1, x2]]
Y = test[[y]]
regr = linear_model.LinearRegression()
regr.fit(X, Y)
model = sm.OLS(Y, X).fit()
predictions = model.predict(X)
print_model = model.summary()
print(print_model)
#===========================================================================
perform_regression_multiple(\'Stock_Index_Price\', \'Interest_Rate\', \'Unemployment_Rate\')
但是,当我尝试使用上述函数执行线性回归(例如,使用 \'Interest_Rate\' 作为唯一解释变量)时,我会收到以下错误消息:
perform_regression_multiple(\'Stock_Index_Price\', \'Interest_Rate\')
KeyError: \"[\'\'] 不在索引中\"
显然,x1 和 x2 都需要指定;否则它将无法正常工作。我应该如何以允许我指定解释变量数量的方式修改函数?目标是通过其他因素扩展回归模型。
非常感谢您的任何建议!
标签: python pandas function linear-regression statsmodels