All sample questions / pandas

pandas Merge, Join and Concat, what does print(merged.shape) print after left = pd.DataFrame({'k': [1, 1, 2], 'a': ['a1', 'a2', 'a3']})?

Block 5, Merge, Join and Concat, question 11 of the pandas sample

import pandas as pd
left = pd.DataFrame({'k': [1, 1, 2], 'a': ['a1', 'a2', 'a3']})
right = pd.DataFrame({'k': [1, 1, 3], 'b': ['b1', 'b2', 'b3']})
merged = pd.merge(left, right, on='k')
print(merged.shape)

What does this print?

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

Answer, C. (4, 3)

A. (3, 3)
Treats the merge as if only one pair of the duplicated key had matched instead of every combination of the two occurrences on each side.
B. (6, 3)
Multiplies as if every key, not just the duplicated one, produced several matches.
C. (4, 3)
Correct. Key 1 appears twice on each side, so an inner join produces two times two, four matching rows for that key alone, while keys 2 and 3 have no match on the other side and are dropped, giving four rows in total.
D. (2, 3)
Assumes duplicate keys line up pairwise instead of multiplying, as if row order matched row order across the two frames.

When a key value is duplicated on both sides of a merge, every occurrence on the left is paired with every occurrence on the right, so the number of matching rows is the product of how many times the key appears on each side. A key present on only one side contributes nothing to an inner join.

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.