You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅忽略KPSS测试中的InterpolationWarning而不影响其他警告?

问题

运行以下Python代码时出现特定警告:

import numpy as np
from statsmodels.tsa.stattools import kpss
kpss(np.random.choice(range(-1000,1000),10000))

警告信息:

<stdin>:1: InterpolationWarning: The test statistic is outside of the range of p-values available in the
look-up table. The actual p-value is greater than the p-value returned.

能否仅忽略该警告,同时不影响代码其他部分的其他警告显示?

解决方案

可以通过Python的warnings模块精准过滤特定类型的警告,不影响其他警告的显示,具体实现方式有两种:

全局临时忽略

如果希望在整个代码执行过程中都忽略该警告,可导入对应警告类并设置过滤规则:

import numpy as np
from statsmodels.tsa.stattools import kpss
import warnings
from statsmodels.tools.sm_exceptions import InterpolationWarning

# 仅忽略InterpolationWarning类型的警告
warnings.filterwarnings("ignore", category=InterpolationWarning)

# 执行代码时不会触发目标警告,但其他警告正常显示
kpss(np.random.choice(range(-1000,1000),10000))

局部代码块忽略(推荐)

如果只想在调用kpss的代码段内忽略警告,执行完后恢复原有警告规则,使用上下文管理器更安全:

import numpy as np
from statsmodels.tsa.stattools import kpss
import warnings
from statsmodels.tools.sm_exceptions import InterpolationWarning

# 仅在该代码块内屏蔽目标警告
with warnings.catch_warnings():
    warnings.filterwarnings("ignore", category=InterpolationWarning)
    result = kpss(np.random.choice(range(-1000,1000),10000))

# 代码块外的其他警告会正常触发
# 示例:触发其他类型警告(仅作演示)
np.sqrt(-1)

两种方式都只会屏蔽InterpolationWarning,代码其他部分出现的其他警告会正常显示。

内容的提问来源于stack exchange,提问作者Brian Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 11:33:17