SettingWithCopyWarning (pandas)
You wrote to a slice of a DataFrame, and pandas cannot promise the write reached the original. Do the selection and the assignment in one .loc call.
Updated
The error
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
What it means
This is a warning, not a crash. It fires when you write to a DataFrame that came from slicing another DataFrame. Pandas cannot tell whether that slice is a view (a window into the original data) or a copy (independent data). If it is a copy, your assignment lands on a throwaway object and the original never changes. That is the silent bug this warning exists to catch.
Why it happens
The classic trigger is chained indexing — two selection operations in one line:
df[df["city"] == "Pune"]["price"] = 0 # writes into a temporaryThe first df[...] returns a new object. The second ["price"] = 0 writes into that temporary, which is then discarded.
The two-step version has the same problem, spread across lines:
pune = df[df["city"] == "Pune"] # a slice
pune["price"] = 0 # is pune a view or a copy?How to fix it
1. Do the row selection and the assignment in one .loc call. This is the fix for the chained case.
df.loc[df["city"] == "Pune", "price"] = 0One operation, one target, no ambiguity. The original df is updated.
2. If you wanted an independent table, say so with .copy().
pune = df[df["city"] == "Pune"].copy()
pune["price"] = 0 # no warning, and separate on purposeUse this when the sliced frame is the thing you will keep working with.
3. Turn on copy-on-write to make the behaviour predictable.
import pandas as pd
pd.set_option("mode.copy_on_write", True)With copy-on-write, every slice behaves like a copy, and chained assignment reliably does nothing instead of sometimes working. Pandas 3 makes this the only behaviour, so opting in now future-proofs your code. Under pandas 2.2+ you may see a FutureWarning pointing at the same change.
How to prevent it
Decide at the moment you slice: is this a filter I will assign through, or a new table? Filters get .loc[mask, col] = value. New tables get .copy(). Never write df[a][b] = value — two selection brackets on the left of an = is always wrong.