All sample questions / pandas

pandas Reshaping, Pivot and Melt, what does print(sorted_df.shape) print after df = pd.DataFrame({'a': [1, 1, 2], 'b': [3, 1, 2], 'orig': [0, 1, 2]})?

Block 6, Reshaping, Pivot and Melt, question 15 of the pandas sample

import pandas as pd
df = pd.DataFrame({'a': [1, 1, 2], 'b': [3, 1, 2], 'orig': [0, 1, 2]})
sorted_df = df.sort_values('a')
print(sorted_df.shape)

What does this print?

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

Answer, C. (3, 3)

A. (1, 3)
Assumes sorting collapses rows that tie on the sort key into a single row.
B. (3, 2)
Assumes sorting drops the column that was sorted on, as if it were consumed by the operation.
C. (3, 3)
Correct. sort_values only reorders the existing rows, it never adds or removes rows or columns, so a three row, three column frame stays three by three after sorting.
D. (2, 3)
Confuses the row and column counts, as though sorting transposed the frame.

sort_values is a pure reordering operation on the existing rows, it changes the sequence in which rows appear but never their number, and it never touches the set of columns at all. Any operation that would change the shape of a frame, like dropping duplicates or aggregating, is a separate step from sorting.

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.