SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
1 · The lesson
readWhat this error means
This is a warning, not an error. Your code keeps running. pandas is telling you that you changed a DataFrame that came from filtering or selecting part of another DataFrame, and it can't be sure which one you meant to change: the small one, or the original. Sometimes the change reaches the original and sometimes it doesn't, depending on how pandas stored the data. The warning exists because code that looks right can silently do nothing.
When you see it
main.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 passed["grade"] = "pass"
The first line gives the file and line number. The last line shows the code that caused it.
In pandas 3.0 and newer this warning no longer exists. The case where the change is lost shows a different warning instead, ChainedAssignmentError (see below).
Why it happens
Two patterns cause almost every case.
1. You filtered, then changed the result. df[df["score"] > 60] gives you some of the rows. Adding a column to that result is fine if you only want to change the filtered rows. pandas warns because it can't know that was your plan.
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus"], "score": [91, 78, 55]}) passed = df[df["score"] > 60] passed["grade"] = "pass" # SettingWithCopyWarning print(passed.shape) # (2, 3): passed has the new column print(df.shape) # (3, 2): df does not
2. Two sets of square brackets in one assignment. This is called chained assignment. The first [...] makes a temporary DataFrame, and the second [...] changes that temporary one, which is then thrown away. The original is not changed.
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus"], "score": [91, 78, 55]}) df[df["score"] < 60]["score"] = 60 # SettingWithCopyWarning print(df["score"].tolist()) # [91, 78, 55]: nothing changed
The second pattern is the dangerous one. The code reads like it sets Linus's score to 60, and it doesn't.
How to fix it
To change the original DataFrame, use .loc in one step. Put the row filter and the column name inside the same .loc[...]:
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus"], "score": [91, 78, 55]}) df.loc[df["score"] < 60, "score"] = 60 print(df["score"].tolist()) # [91, 78, 60]
To work on the filtered rows as a separate table, say so with .copy(). Then the new DataFrame is clearly yours, and pandas has nothing to warn about:
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus"], "score": [91, 78, 55]}) passed = df[df["score"] > 60].copy() passed["grade"] = "pass" # no warning print(passed) # name score grade # 0 Ada 91 pass # 1 Grace 78 pass
To add a column to every row based on a condition, don't filter first. Build the whole column in one go:
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus"], "score": [91, 78, 55]}) df["grade"] = "fail" df.loc[df["score"] > 60, "grade"] = "pass" print(df["grade"].tolist()) # ['pass', 'pass', 'fail']
In pandas 3.0 and newer, a filtered DataFrame always behaves as a separate copy (pandas calls this Copy-on-Write). Pattern 1 then works without a warning, and you no longer need .copy() just to silence it. Pattern 2 still changes nothing, and pandas 3 warns about it with ChainedAssignmentError: A value is being set on a copy of a DataFrame or Series through chained assignment. The .loc fix above is the same in every version.
When you'd see this in real code
- Cleaning data step by step:
clean = df[df["country"] == "UK"], thenclean["price"] = clean["price"].round(2). - A function receives part of a DataFrame from its caller and adds a column to it.
df[df["age"].isna()]["age"] = 0meant to fill missing ages, and the ages are still missing afterwards.- Selecting columns with
subset = df[["name", "score"]]and then changingsubset.
Related errors
- AttributeError: 'DataFrame' object has no attribute 'append': another pandas change between versions.
- ValueError: Length of values does not match length of index: adding a column whose length doesn't fit the DataFrame.
- ValueError: The truth value of a Series is ambiguous: using
and,ororifwith a pandas condition. - KeyError: the column name you used doesn't exist.
See Also
- All Python errors: the full index, by type and by when it happens.
- pandas (tutorial)
- pandas cheat sheet
- Data science with pandas
Found this useful? Share it with a friend who’s learning Python.