As this question is already fully explained and discussed in existing answers I will just provide a neat pandas
approach to the context manager using pandas.option_context
(links to docs and example) - there is absolutely no need to create a custom class with all the dunder methods and other bells and whistles.
First the context manager code itself:
from contextlib import contextmanager
@contextmanager
def SuppressPandasWarning():
with pd.option_context("mode.chained_assignment", None):
yield
Then an example:
import pandas as pd
from string import ascii_letters
a = pd.DataFrame({"A": list(ascii_letters[0:4]), "B": range(0,4)})
mask = a["A"].isin(["c", "d"])
# Even shallow copy below is enough to not raise the warning, but why is a mystery to me.
b = a.loc[mask] # .copy(deep=False)
# Raises the `SettingWithCopyWarning`
b["B"] = b["B"] * 2
# Does not!
with SuppressPandasWarning():
b["B"] = b["B"] * 2
Worth noticing is that both approches do not modify a
, which is a bit surprising to me, and even a shallow df copy with .copy(deep=False)
would prevent this warning to be raised (as far as I understand shallow copy should at least modify a
as well, but it doesn't. pandas
magic.).