Skip to content

BUG: Using .loc raises SettingWithCopyWarning #41309

@ad12

Description

@ad12
  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

# Your code here
res = pd.DataFrame({"Method": ["Alpha1", "Beta1", "Beta2", "Alpha2", "Alpha3"], "Value": [5, 6, 7, 8, 10]})
df = res[res["Value"] <= 8]
df.loc[df["Method"].str.contains("Alpha"), "Method"] = "Gamma"

display(res)
display(df)

Problem description

In the code above, we are:

  1. Creating a new dataframe res
  2. Getting a copy of the dataframe where values are less than 8 and assigning that to df
  3. Setting values in df using the .loc indexing

Step 3 raises the SettingWithCopyWarning. I don't believe we are setting the value of a copy there as we are using the .loc indexing method, which should set values in df. The values are being set, but the warning is being raised. If I'm understand the warning correctly, it should not be raised.

Expected Output

No warning should be raised

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 2cb9652
python : 3.7.9.final.0
python-bits : 64
OS : Linux
OS-release : 5.8.0-50-generic
Version : #56~20.04.1-Ubuntu SMP Mon Apr 12 21:46:35 UTC 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : en_US.UTF-8
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.2.4
numpy : 1.19.1
pytz : 2020.1
dateutil : 2.8.1
pip : 20.2.2
setuptools : 49.6.0.post20200814
Cython : None
pytest : 6.2.1
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.18.1
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.3.1
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.5.2
sqlalchemy : None
tables : None
tabulate : 0.8.7
xarray : None
xlrd : None
xlwt : None
numba : 0.51.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Closing CandidateMay be closeable, needs more eyeballs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions