All sample questions / pandas

What does print(list(combined.columns)) print? pandas Merge, Join and Concat

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

import pandas as pd
a = pd.DataFrame({'x': [1, 2]})
b = pd.DataFrame({'y': [3, 4]})
combined = pd.concat([a, b], axis=1)
print(list(combined.columns))

What does this print?

  1. A. ['x_x', 'y_y']
  2. B. ['x', 'x']
  3. C. ['y', 'x']
  4. D. ['x', 'y']
Show the answer and why each option is right or wrong

Answer, D. ['x', 'y']

A. ['x_x', 'y_y']
Assumes overlapping column positions get suffixed the way a merge would, even though these two column names do not actually collide.
B. ['x', 'x']
Assumes axis=1 still stacks the frames as rows and repeats the same column name for both.
C. ['y', 'x']
Reverses the order the two frames were listed in.
D. ['x', 'y']
Correct. Concatenating along axis=1 places the frames side by side as new columns rather than stacking rows, and since the two frames have different column names, x and y, both survive unchanged.

concat with axis=1 aligns the inputs on their index and places their columns next to each other, it does not rename or merge columns the way pd.merge does. Column name collisions are only a problem if two of the concatenated frames actually share a column label, which x and y here do not.

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.