/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:
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.pyOutput
/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
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
sub = df[df["a"] > 1].copy()
sub["b"] = 0 # changes only sub, no warningSources
Related pages
changes · pandaspandas 2 to 3: Copy-on-Write, the str dtype and other breaking changespandas 3.0 makes Copy-on-Write the only mode, infers strings as the new str dtype, drops SettingWithCopyWarning and needs Python 3.11+. Shown side by side.compare · pandaspandas loc vs iloc: label-based vs position-based selectionloc selects rows and columns by label and includes the end of a slice; iloc selects by integer position and excludes it. Cases where they return different rows.cheat sheets · pandaspandas cheat sheet: read, select, filter, group and reshapepandas cheat sheet: read CSV and Parquet, select with loc and iloc, filter rows, add columns, group and aggregate, pivot, handle missing values and write files.