1. Home
  2. Interview Questions
  3. Python
  4. 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

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best 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:

  1. df.__getitem__(mask) returns a new object.
  2. __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'] = x or df['col'][idx] = x.
  • Hidden chaining across lines: sub = df[df['city'] == 'Pune'], followed later by sub['bonus'] = 100. Pandas remembers that sub came from df. It cannot know whether you expected df to 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 on df.
  • You want an independent subset: make the intent explicit with sub = df[mask].copy(). Changes to sub then never affect df, 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 .loc anywhere in the chain makes it safe. df.loc[mask]['col'] = x is 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_index or rename in terms of memory?
  • What is the difference between .loc, .iloc and .at when 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

All hard questions →

Related Questions

‹
Q9 of 10 · Python
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA