- Home
- Interview Questions
- Python
- Why does Pandas raise SettingWithCopyWarning and how do you …
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: The warning appears when you assign to something that may be a temporary copy of a DataFrame, usually through chained indexing like df[mask]['col'] = value. The original data may not change. Fix it with a single .loc call on the original, or call .copy() when you deliberately want an independent subset.
Detailed explanation
Look at df[df['age'] > 30]['salary'] = 0. Python runs this as two separate operations:
df.__getitem__(mask)returns a new object.__setitem__('salary', 0)is then called on that new object.
Whether the first step returns a view or a copy depends on internal details. These include the indexer type, the dtypes and the memory layout. Boolean masks almost always produce a copy. In that case the assignment modifies a temporary object, and the result is thrown away. df stays unchanged and you get no error.
Pandas cannot reliably tell whether you meant to modify the original. So it raises SettingWithCopyWarning as a heuristic. The warning shows up in two typical situations:
- Chained assignment on one line:
df[mask]['col'] = xordf['col'][idx] = x. - Hidden chaining across lines:
sub = df[df['city'] == 'Pune'], followed later bysub['bonus'] = 100. Pandas remembers thatsubcame fromdf. It cannot know whether you expecteddfto change.
The fixes depend on what you intend:
- You want to modify the original: use one indexing call that names both rows and columns, such as
df.loc[mask, 'col'] = x. This calls__setitem__directly ondf. - You want an independent subset: make the intent explicit with
sub = df[mask].copy(). Changes tosubthen never affectdf, and no warning is raised.
Copy-on-Write (CoW). pandas 2.x includes Copy-on-Write as an opt-in mode via pd.options.mode.copy_on_write = True, and it is planned to become the default in pandas 3.0. Under CoW, every indexing result behaves as a copy, and data is physically copied only when someone writes to it. Chained assignment then never updates the original, and pandas warns about it. The view-or-copy ambiguity goes away, but .loc remains the only correct way to update the parent.
Example
import pandas as pd
df = pd.DataFrame({'name': ['A', 'B', 'C'],
'age': [25, 35, 45],
'salary': [30, 50, 70]})
# Wrong: chained assignment, df may not change
df[df['age'] > 30]['salary'] = 0 # SettingWithCopyWarning
# Right: single .loc call on the original
df.loc[df['age'] > 30, 'salary'] = 0
# Wrong: subset later modified, intent unclear
seniors = df[df['age'] > 30]
seniors['bonus'] = 10 # warning
# Right: explicit independent copy
seniors = df[df['age'] > 30].copy()
seniors['bonus'] = 10 # df untouched, no warning
# Alternative that returns a new frame, no mutation
seniors = df[df['age'] > 30].assign(bonus=10)Common mistakes
- Silencing it with
pd.options.mode.chained_assignment = None. This hides the warning but not the bug, and updates still get lost. - Believing that
.locanywhere in the chain makes it safe.df.loc[mask]['col'] = xis still chained. Rows and columns must go in the same.loc[rows, cols]call. - Assuming the warning only appears on the line that caused the problem. It often fires several lines after the subset was created, so trace back to where the slice was taken.
- Calling
.copy()on large frames out of habit when you actually wanted to modify the original. That wastes memory and leaves the source unchanged.
Follow-up questions
- When does basic slicing in NumPy return a view, and how can you check it with
np.shares_memory? - How does Copy-on-Write change the behaviour of methods like
reset_indexorrenamein terms of memory? - What is the difference between
.loc,.ilocand.atwhen assigning a single value?
Interview tip: Say it plainly: chained indexing is two calls, and the second one may write to a temporary copy. Then show the one-line .loc fix. That shows you understand the mechanism, not just the remedy.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More hard Python questions
Related Questions
- What is the difference between assignment, shallow copy and deep copy in Python? · Python · 1 ans
- What is broadcasting in NumPy and what rules decide whether two arrays can be combined? · Python · 1 ans
- How do positional-only (/) and keyword-only (*) parameters work in Python function signatures? · Python · 1 ans
- Why does using a mutable default argument like a list cause bugs in Python? · Python · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- What is exception chaining in Python and when should you use raise from? · Python · 1 ans
- In what order do try, except, else and finally blocks run in Python? · Python · 1 ans
- Why do lambdas created inside a loop all return the last loop value in Python? · Python · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)