All sample questions / pandas

What does print(df['b'].tolist()) print? pandas Copy-on-Write, Views and Assignment

Block 7, Copy-on-Write, Views and Assignment, question 16 of the pandas sample

import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [7, 8, 9]})
df.loc[df['a'] > 1, 'b'] = 0
print(df['b'].tolist())

What does this print?

  1. A. ChainedAssignmentError
  2. B. [7, 8, 9]
  3. C. [7, 0, 0]
  4. D. [0, 0, 0]
Show the answer and why each option is right or wrong

Answer, C. [7, 0, 0]

A. ChainedAssignmentError
Assumes this recommended single step pattern still triggers the warning that chained assignment triggers.
B. [7, 8, 9]
Assumes a loc based write is chained the same way df[mask][col] is, and gets silently dropped.
C. [7, 0, 0]
Correct. df.loc[mask, 'b'] = 0 addresses both the rows and the column in one call on df itself, so it is a direct write that succeeds, giving [7, 0, 0].
D. [0, 0, 0]
Assumes the write reaches every row of the column instead of only the rows selected by the mask.

The documentation for chained assignment recommends exactly this pattern, .loc[row_indexer, col_indexer] = value, because it resolves the row selection and the column selection in one call rather than two separate bracket lookups. It writes straight into df with no intermediate object involved.

The answer above is what pandas 3.0.5 printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 255 pandas interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 255 pandas questions, 9 euros

Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros

Or play the free pandas sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.