如何将adfuller_test遍历DataFrame列的打印输出保存为PDF或TXT文件
解决ADF检验输出保存到本地文件的方案
方案1:直接保存为TXT文件(改动最少)
无需修改原有adfuller_test函数,直接捕获终端打印内容写入TXT,输出和终端显示完全一致:
from contextlib import redirect_stdout # 所有打印输出会直接写入ADF检验结果.txt with open('ADF检验结果.txt', 'w', encoding='utf-8') as f: with redirect_stdout(f): for name, column in train_set.iteritems(): adfuller_test(column, name=column.name)
方案2:生成PDF文件
如果需要PDF格式,先把所有输出捕获到内存,再逐行写入PDF即可:
- 先安装依赖:
pip install fpdf2 - 运行如下代码:
from contextlib import redirect_stdout import io from fpdf import FPDF # 捕获所有打印输出到内存字符串 output_buffer = io.StringIO() with redirect_stdout(output_buffer): for name, column in train_set.iteritems(): adfuller_test(column, name=column.name) all_content = output_buffer.getvalue() content_lines = all_content.split('\n') # 生成PDF文件 pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) # 逐行写入内容,行高设为7适配字体大小 for line in content_lines: pdf.cell(200, 7, txt=line if line.strip() else ' ', ln=1, align='L') pdf.output("Augmented Dickey Fuller Test.pdf")
可选优化:修改adfuller_test返回结果字符串
如果不想用标准输出捕获的方式,可以修改原函数,直接返回检验报告的字符串,后续处理更灵活:
def adfuller_test(series, signif=0.05, name='', verbose=False): """Perform ADFuller to test for Stationarity of given series and return report string""" r = adfuller(series, autolag='AIC') output = {'test_statistic':round(r[0], 4), 'pvalue':round(r[1], 4), 'n_lags':round(r[2], 4), 'n_obs':r[3]} p_value = output['pvalue'] def adjust(val, length= 6): return str(val).ljust(length) res = [] res.append(f' Augmented Dickey-Fuller Test on "{name}"' + "\n " + '-'*47) res.append(f' Null Hypothesis: Data has unit root. Non-Stationary.') res.append(f' Significance Level = {signif}') res.append(f' Test Statistic = {output["test_statistic"]}') res.append(f' No. Lags Chosen = {output["n_lags"]}') for key,val in r[4].items(): res.append(f' Critical value {adjust(key)} = {round(val, 3)}') if p_value <= signif: res.append(f" => P-Value = {p_value}. Rejecting Null Hypothesis.") res.append(f" => Series is Stationary.") else: res.append(f" => P-Value = {p_value}. Weak evidence to reject the Null Hypothesis.") res.append(f" => Series is Non-Stationary.") return '\n'.join(res)
修改后可以直接在循环中收集所有列的检验结果,再写入TXT或PDF即可。
内容的提问来源于stack exchange,提问作者Lachlan Sweet
相关产品推荐
相关产品推荐

