Skip to content

/errors/pandas/settingwithcopywarning

SettingWithCopyWarning: A value is trying to be set on a copy of a slice

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated 2026-10-20
tool
pandas
exit code
0
versions
pandas 1.x – 2.x (removed in 3.0)
os
any

pandas 1.x and 2.x print SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame when you assign values to a subset that may be a copy of the original, so the assignment might not change the data you expect. Do the assignment on the original with .loc, or take an explicit .copy(). pandas 3.0 removed the warning: with Copy-on-Write every subset behaves as a copy.

Reproduce it, and see pandas 3 behave differently

The same script with pandas 2.2.3 (through uv) and with pandas 3:

bash
cat > cow.py <<'PY'
import warnings, pandas as pd
warnings.simplefilter("always")
df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
sub = df[df["a"] > 1]
sub["b"] = 0
print("pandas", pd.__version__, "original b:", df["b"].tolist())
PY
uv run -q --no-project --python 3.13 --with pandas==2.2.3 python cow.py
python cow.py

Output

/tmp/work/cow.py:5: 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
  sub["b"] = 0
pandas 2.2.3 original b: [10, 20, 30]
pandas 3.0.6 original b: [10, 20, 30]

In both versions the original df is unchanged: sub is a separate object. pandas 2 warns because it cannot always tell; pandas 3 guarantees it and stays silent.

Fix: assign on the original with .loc

bash
python -c '
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
df.loc[df["a"] > 1, "b"] = 0
print(df["b"].tolist())'

Output

[10, 0, 0]

Fix: work on an explicit copy

python
sub = df[df["a"] > 1].copy()
sub["b"] = 0          # changes only sub, no warning

Sources