Python时间序列项目报错:name 'result' is not defined 求解决
修复ADF检验代码中的NameError错误
错误原因
result是adfuller_test函数内部定义的局部变量,函数外部的代码无法直接访问这个变量,所以第8行的if result[1] <= 0.05会触发NameError。
修复方案
方案1:让函数返回结果,外部接收后判断
修改函数使其返回result,在调用时接收返回值再进行判断:
from statsmodels.tsa.stattools import adfuller def adfuller_test(GDP): result = adfuller(GDP) labels = ['ADF Test Statistic','p-value','#Lags Used','Number of Observations'] for value, label in zip(result, labels): print(f"{label} : {value}") return result # 返回检验结果 # 调用函数并保存结果 result = adfuller_test(data['GDP']) # 基于返回值判断平稳性 if result[1] <= 0.05: print("strong evidence against the null hypothesis(Ho), reject the null hypothesis. Data is stationary") else: print("weak evidence against null hypothesis,indicating it is non-stationary ")
方案2:将判断逻辑移到函数内部
把平稳性判断的代码放到函数里,直接在函数内处理结果:
from statsmodels.tsa.stattools import adfuller def adfuller_test(GDP): result = adfuller(GDP) labels = ['ADF Test Statistic','p-value','#Lags Used','Number of Observations'] for value, label in zip(result, labels): print(f"{label} : {value}") # 函数内部直接判断并输出结论 if result[1] <= 0.05: print("strong evidence against the null hypothesis(Ho), reject the null hypothesis. Data is stationary") else: print("weak evidence against null hypothesis,indicating it is non-stationary ") adfuller_test(data['GDP'])
额外提醒
确保已经导入statsmodels库中的adfuller工具,否则会出现另一个NameError(找不到adfuller)。如果还没安装statsmodels,可以用命令pip install statsmodels安装。
内容的提问来源于stack exchange,提问作者Pranav Jaswal
相关产品推荐
相关产品推荐

