解决创建多元回归函数时出现的unhashable type: 'list'错误
解决「unhashable type: 'list'」错误的多元回归函数修正
我来帮你搞定这个问题!你遇到的「unhashable type: 'list'」错误,根源是选取自变量列的写法出了问题。
错误原因分析
你写了 X = df_crypto[[independent_variables]],如果 independent_variables 是一个列表(比如 ["BTC", "ETH", "XRP"]),双层方括号会把整个列表当成一个单独的键去查找——但列表是不可哈希的类型,pandas根本没法用它去匹配列名,自然就报错了。
修正后的完整代码
import statsmodels.api as sm import pandas as pd # 读取所有日期的收益率数据 df_crypto = pd.read_csv(r'F:Data/returns_on_all_dates.csv', index_col=0) def perform_multiple_regression(dependant_variable, independent_variables): # 修正:直接用单层方括号传入自变量列名列表 X = df_crypto[independent_variables] y = df_crypto[dependant_variable] # 给自变量添加截距项 X = sm.add_constant(X) # 拟合多元回归模型并输出结果 model = sm.OLS(y, X).fit() print(model.summary()) # 返回模型对象方便后续分析 return model
额外注意点
- 原代码里的
df_crypto.head()只是查看数据前几行,放在函数里不会有输出也不影响逻辑,要是需要看数据可以改成print(df_crypto.head()),或者移到函数外面执行 - 调用函数时,确保
dependant_variable是单个列名字符串(比如"纳斯达克"),independent_variables是列名列表(比如["BTC", "ETH", "XRP"])
内容的提问来源于stack exchange,提问作者Yue TANG
相关产品推荐
相关产品推荐

