All sample questions / pandas
What does print(df['a'].tolist()) print? pandas Copy-on-Write, Views and Assignment
Block 7, Copy-on-Write, Views and Assignment, question 18 of the pandas sample
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3]})
df.loc[:, 'a'] = df['a'] * 10
print(df['a'].tolist())
What does this print?
Show the answer and why each option is right or wrong
Answer, C. [10, 20, 30]
- A. [10, 10, 10]
- Assumes every entry of the column ends up with the same value instead of each one being multiplied by ten individually.
- B. None
- Confuses the effect of the assignment on df with the return value of the statement itself, which prints nothing at all.
- C. [10, 20, 30]
- Correct. df.loc[:, 'a'] = ... is a single step write directly on df, so the whole column is replaced with its values multiplied by ten, giving [10, 20, 30].
- D. [1, 2, 3]
- Assumes this loc based write is somehow chained and gets silently dropped the way df[mask][col] would be.
Using .loc with both a row selector and a column label on the left of an assignment addresses df directly in one call, exactly like the recommended fix for chained assignment. Reading df['a'] on the right hand side happens first and does not itself create any lasting alias, so the multiplication result is written straight into df's own column.
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.