All sample questions / pandas

What does print(df.iloc[-1]['a']) print? pandas Selecting with loc, iloc and Masks

Block 2, Selecting with loc, iloc and Masks, question 5 of the pandas sample

import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}, index=[10, 20, 30])
print(df.iloc[-1]['a'])

What does this print?

  1. A. 10
  2. B. 2
  3. C. 3
  4. D. 1
Show the answer and why each option is right or wrong

Answer, C. 3

A. 10
Returns the index label of the last row instead of its a value.
B. 2
Reads the middle row instead of the last one.
C. 3
Correct. iloc[-1] takes the last row by position regardless of its label, and that row has an a value of 3.
D. 1
Reads the first row instead of the last one.

Negative positions with iloc count backward from the end exactly the way they would in a plain Python list, entirely independent of what the row labels are. The row label 30 has no bearing on which row -1 refers to.

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.