This article explains how to turn off warnings in JupyterLab and Jupyter Notebook. JupyterLab warnings can be extremely useful and prevent unexpected behaviour.
But there are some cases when you would like to turn them off completely or for a given cell.
In order to demo the solution we would use the next code example:
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
this will generate warning like:
<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
Method 1: Suppress warnings for a code statement
First we will show how to hide warnings messages for a single cell in a Jupyter Notebook.
This can be done by adding next code:
import warnings with warnings.catch_warnings(record=True): df[df.A > 5]['B'] = 4
warnings.catch_warnings(record=True): will hide all warnings in the scope.
1.2 Using warnings.simplefilter('once')
Another option is to use
warnings.simplefilter('ignore') in order to suppress warnings.
The code below will not produce warning message:
import warnings with warnings.catch_warnings(): warnings.simplefilter('ignore') df[df.A > 5]['B'] = 4
Method 2: Turn off warnings for a single cell
If you like to hide warnings only for a single cell and yet display output in JupyterLab then you can use
%%capture --no-display. So cell like:
%%capture --no-display df[df.A > 5]['B'] = 4 1
will show only 1 as output. There are other useful option for this function like:
- Don’t capture stderr.
- Don’t capture stdout.
- Don’t capture IPython’s rich display.
The explanation is available on this link: Cell magics %%capture
Method 3: Turn off warnings completely for the Notebook
To stop warnings for the whole Notebook you can use the method
filterwarnings. It has two useful options:
import warnings warnings.filterwarnings('ignore')
This will hide all Jupyter Notebook warnings.
If you like to see the warnings just once then use:
import warnings warnings.filterwarnings(action='once')
action='once' might not work in some cases.