【发布时间】:2021-11-21 17:20:24
【问题描述】:
我在数据框中的列上迭代一个函数,如下所示:
for name, column in train_set.iteritems():
adfuller_test(column, name=column.name)
我想将这些迭代的输出保存到外部文件,无论是 .txt 还是 .pdf 格式。我发现了这种从脚本创建 PDF 文件的方法:
import fpdf
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt=print(), ln=1, align="C")
pdf.output("Augmented Dickey Fuller Test.pdf")
但是,如何将 for 循环的输出带入 txt?我尝试使用list.append 将循环结果存储在列表中,但不幸的是adfuller_test 函数返回NoneType 对象。
更新:adfuller_test 对时间序列数据执行增强的 Dickey Fuller 测试。函数定义为:
def adfuller_test(series, signif=0.05, name='', verbose=False):
"""Perform ADFuller to test for Stationarity of given series and print report"""
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)
print(f' Augmented Dickey-Fuller Test on "{name}"', "\n ", '-'*47)
print(f' Null Hypothesis: Data has unit root. Non-Stationary.')
print(f' Significance Level = {signif}')
print(f' Test Statistic = {output["test_statistic"]}')
print(f' No. Lags Chosen = {output["n_lags"]}')
for key,val in r[4].items():
print(f' Critical value {adjust(key)} = {round(val, 3)}')
if p_value <= signif:
print(f" => P-Value = {p_value}. Rejecting Null Hypothesis.")
print(f" => Series is Stationary.")
else:
print(f" => P-Value = {p_value}. Weak evidence to reject the Null Hypothesis.")
print(f" => Series is Non-Stationary.")
当在系列上运行时,它会打印以下输出(示例):
Null Hypothesis: Data has unit root. Non-Stationary.
Significance Level = 0.05
Test Statistic = -0.5388
No. Lags Chosen = 2
Critical value 1% = -3.437
Critical value 5% = -2.864
Critical value 10% = -2.568
=> P-Value = 0.8842. Weak evidence to reject the Null Hypothesis.
=> Series is Non-Stationary.
脚本循环遍历一个有 30 列的 DataFrame,因此返回 30 个这样的输出。我想做的是将这些输出存储在一个文件中,因为它们打印在终端窗口中。文件格式无关紧要,.txt 文件也可以。
【问题讨论】:
-
您不应该保存为 pdf 文件,pdf 是一种显示格式,而不是用于将数据保存到磁盘(您似乎想要的)。
-
您应该准确说明
adfuller_test所做的和返回的内容以及您要保存的内容。 -
@LouisLac 我已更新问题以阐明函数的输出以及文件中应保存的内容(任何可读格式都有效)
-
您可以将“打印”重定向到一个文件,例如这; stackoverflow.com/questions/4675728/…