如何关闭JupyterLab和 Jupyter Notebook中的警告?

4,873 阅读2分钟

How to Turn off Warnings in JupyterLab(Jupyter Notebook)

本文介绍了如何关闭JupyterLab和Jupyter Notebook中的警告。JupyterLab的警告可能非常有用,可以防止意外行为的发生。
但在某些情况下,你想完全关闭它们,或者关闭某个单元的警告。

为了演示这个解决方案,我们将使用下面的代码示例。

import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (3, 5)), columns=list('ABCDE'))

df[df.A > 5]['B'] = 4

这将产生类似的警告。

<ipython-input-11-16e42a61bea5>:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df[df.A > 5]['B'] = 4

方法1:抑制一个代码语句的警告

1.1 warnings.catch_warnings(record=True)

首先我们将展示如何隐藏Jupyter笔记本中单个单元格的警告信息。

这可以通过添加以下代码来实现。

import warnings

with warnings.catch_warnings(record=True):
    df[df.A > 5]['B'] = 4

添加上下文warnings.catch_warnings(record=True): ,将隐藏该范围内的所有警告信息。

1.2 使用 warnings.simplefilter('once')

另一个选择是使用warnings.simplefilter('ignore') ,以抑制警告。

下面的代码将不会产生警告信息。

import warnings
with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    df[df.A > 5]['B'] = 4

方法2:关闭单个单元格的警告

如果你想只隐藏一个单元格的警告,但又想在JupyterLab中显示输出,那么你可以使用%%capture --no-display 。因此,像这样的单元格。

%%capture --no-display
df[df.A > 5]['B'] = 4
1

将只显示1的输出。这个函数还有其他有用的选项,比如。

  • --no-stderr

    • 不要捕获stderr。
  • --no-stdout

    • 不要捕获stdout。
  • --no-display

    • 不要捕捉IPython的丰富显示。

该解释可在此链接中找到。Cell magics %%capture

How to Turn off Warnings in JupyterLab(Jupyter Notebook)

方法3:完全关闭笔记本的警告

要停止整个笔记本的警告,你可以使用filterwarnings 。它有两个有用的选项。

import warnings
warnings.filterwarnings('ignore')

这将隐藏所有Jupyter笔记本的警告。

如果你想只看一次警告,那么使用:

import warnings
warnings.filterwarnings(action='once')

注意:action='once' 在某些情况下可能不起作用。