All sample questions / pandas
pandas Strings, Dates and apply, what does print(out.shape) print after df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})?
Block 8, Strings, Dates and apply, question 20 of the pandas sample
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
out = df.apply(lambda r: pd.Series([r['a'] + r['b'], r['a'] * r['b']]), axis=1)
print(out.shape)
What does this print?
Show the answer and why each option is right or wrong
Answer, D. (2, 2)
- A. (2,)
- Assumes returning a Series from the row function still leaves the overall result as a single column Series.
- B. (1, 2)
- Swaps rows and columns, treating the two original rows as if they became two output columns instead of two output rows.
- C. (4, 1)
- Assumes the two values produced per row get stacked into one long column instead of laid out as two columns.
- D. (2, 2)
- Correct. When the function passed to apply with axis=1 returns a Series, pandas lays its values out as columns of a new DataFrame, one row per original row and one column per element of the returned Series, giving a two by two shape.
apply inspects what the row function returns, a scalar produces a plain Series result, but a Series return value gets expanded into a full DataFrame, with the returned index becoming the new columns.
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.
Did this save you a lookup? Buy me a coffee on Ko-fi.