19

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)?

Georgy
  • 12,464
  • 7
  • 65
  • 73
vestland
  • 55,229
  • 37
  • 187
  • 305

2 Answers2

45

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!
Georgy
  • 12,464
  • 7
  • 65
  • 73
  • 1
    Is this up to date? Trying to import SettingWithCopyWarning from pandas.core.common results in: Cannot find reference 'SettingWithCopyWarning' in 'common.py' – Emil Jansson Dec 27 '22 at 10:33
  • 6
    I was able to find the warning here: from pandas.errors import SettingWithCopyWarning – Emil Jansson Dec 27 '22 at 10:36
19

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!
1''
  • 26,823
  • 32
  • 143
  • 200