1. Home
  2. Data Science
  3. Pandas
  4. Under the copy-on-write semantics of pandas 2.x, df[df.a >…

Added 30 Nov -0001

Under the copy-on-write semantics of pandas 2.x, df[df.a > 0]['b'] = 1 is executed. What is the effect?

  1. The whole column b is set to 1 for every row, since the mask is ignored here
  2. Nothing changes in df, because the chained assignment writes to a temporary copy Correct answer
  3. Column b is updated for the matching rows, exactly as an equivalent .loc assignment would
  4. A SettingWithCopyWarning is raised and the assignment is then silently applied

Correct answer

B. Nothing changes in df, because the chained assignment writes to a temporary copy

15 views

MCQSEXAM

Explanation

Copy-on-write makes every derived object a lazy view, so assigning into a temporary such as df[mask]['b'] modifies a copy that is then discarded and the parent stays untouched. Chained assignment is therefore never a valid way to update data; use df.loc[df.a > 0, 'b'] = 1. In pandas 3.0 the behaviour is the default, with no warning to alert you.

Reference

Asked in: NTS, PPSC IT, Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? 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