禁止显示python警告

时间:2019-02-19 14:27:49

标签: python suppress-warnings

当我在for循环中进行迭代时,我不断收到相同的警告,我想取消它。该警告显示为:

use Session

产生警告的代码如下:

C:\Users\Nick Alexander\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\preprocessing\data.py:193: UserWarning: Numerical issues were encountered when scaling the data and might not be solved. The standard deviation of the data is probably very close to 0. warnings.warn("Numerical issues were encountered "

我已经禁用了一个警告。我不想禁用所有警告,我只想禁用此警告。我正在使用python 3.7和sklearn版本0.0

3 个答案:

答案 0 :(得分:7)

import warnings
with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    # code that produces a warning

warnings.catch_warnings()的意思是“无论在该块中运行什么warnings.方法,在退出该块时都将其撤消”。

答案 1 :(得分:1)

在脚本开头尝试以下操作:

import warnings
warnings.filterwarnings("ignore", message="Numerical issues were encountered ")

答案 2 :(得分:0)

python contextlib为此提供了一个contextmamager:suppress

from contextlib import suppress

with suppress(UserWarning):
    for c in cols:
        df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
        df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))