1. Home
  2. Data Science
  3. Pandas
  4. df2 = df[df.a > 0]; df2['b'] = 1; raises…

Added 30 Nov -0001

df2 = df[df.a > 0]; df2['b'] = 1; raises SettingWithCopyWarning. Why?

  1. Because boolean indexing always returns a tuple of arrays, so assignment cannot tell which of the two arrays to modify in place here
  2. Because column b does not exist in df, so pandas must decide whether to create it on the copy or on the parent frame
  3. Boolean indexing returns a new object that may still reference the parent's data, so chained assignment has an ambiguous target Correct answer
  4. Because assigning a scalar to a new column is not allowed after filtering, and pandas raises a warning instead

Correct answer

C. Boolean indexing returns a new object that may still reference the parent's data, so chained assignment has an ambiguous target

12 views

MCQSEXAM

Explanation

SettingWithCopyWarning appears because df[df.a > 0] produces a new DataFrame that may share memory with df, leaving pandas unsure whether the assignment should propagate to the parent. It is a warning rather than an error, and the write may silently fail to affect df. The fix is an explicit df.loc[df.a > 0, 'b'] = 1 on the original, or .copy() when an independent frame is intended.

Reference

Asked in: NTS, PPSC IT, Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More Pandas MCQs

Practise all Pandas MCQs

Similar MCQs