vestland
vestland

Reputation: 61084

How to ignore SettingWithCopyWarning using warnings.simplefilter()?

The question:

Can I ignore or prevent the SettingWithCopyWarning to be printed to the console using warnings.simplefilter()?

The details:

I'm running a few data cleaning routines using pandas, and those are executed in the simplest of ways using a batch file. One of the lines in my Python script triggers the SettingWithCopyWarning and is printed to the console. But it's also being echoed in the command prompt:

enter image description here

Aside from sorting out the source of the error, is there any way I can prevent the error message from being printed to the prompt like I can with FutureWarnings like warnings.simplefilter(action = "ignore", category = FutureWarning)?

Upvotes: 26

Views: 58571

Answers (3)

syd
syd

Reputation: 117

The updated solution to suppress the SettingWithCopyWarning is:

import warnings
import pandas as pd
from pandas.errors import SettingWithCopyWarning
warnings.simplefilter(action='ignore', category=(SettingWithCopyWarning))

Upvotes: 9

Bruno Ruas De Pinho
Bruno Ruas De Pinho

Reputation: 485

You can use:

pd.set_option('mode.chained_assignment', None)
# This code will not complain!
pd.reset_option("mode.chained_assignment")

Or if you prefer to use it inside a context:

with pd.option_context('mode.chained_assignment', None):
    # This code will not complain!

Upvotes: 23

Georgy
Georgy

Reputation: 13697

Though I would strongly advise to fix the issue, it is possible to suppress the warning by importing it from pandas.core.common. I found where it's located on GitHub.

Example:

import warnings

import pandas as pd
from pandas.core.common import SettingWithCopyWarning

warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)

df = pd.DataFrame(dict(A=[1, 2, 3], B=[2, 3, 4]))
df[df['A'] > 2]['B'] = 5  # No warnings for the chained assignment!

Upvotes: 46

Related Questions