df2 = df[df.a > 0]; df2['b'] = 1; raises SettingWithCopyWarning. Why?
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
C. Boolean indexing returns a new object that may still reference the parent's data, so chained assignment has an ambiguous target
12 views
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.
Asked in: NTS, PPSC IT, Interviews
Not sure why the answer is C? Ask here and get an explanation.