All sample questions / pandas

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

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

import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8]})
print(df[df['a'].isin([1, 4])]['b'].tolist())

What does this print?

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

Answer, A. [5, 8]

A. [5, 8]
Correct. isin checks each value of a against the given list and returns True wherever it matches one of the members, so the rows where a is 1 or 4 pass through, giving b values 5 and 8.
B. [6, 7]
Keeps the rows whose a value is not in the list instead of the ones whose value is in it.
C. [5, 6, 7, 8]
Ignores the isin filter entirely and returns every row of b.
D. []
Assumes isin only matches when every value in the column equals every member of the list, so nothing passes.

isin builds a boolean mask by testing membership in a collection, one value at a time, which reads more clearly than chaining several equality comparisons with |. It matches exactly the values listed, nothing more and nothing less.

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.