All sample questions / pandas

What does print(df.groupby('k')['v'].agg(lambda s: (s ** 2).sum()).to_dict()) print? pandas GroupBy and Aggregation

Block 4, GroupBy and Aggregation, question 10 of the pandas sample

import pandas as pd
df = pd.DataFrame({'k': ['a', 'a', 'b'], 'v': [1, 2, 3]})
print(df.groupby('k')['v'].agg(lambda s: (s ** 2).sum()).to_dict())

What does this print?

  1. A. {'a': 5, 'b': 3}
  2. B. {'a': 3, 'b': 3}
  3. C. {'a': 5, 'b': 9}
  4. D. {'a': 9, 'b': 9}
Show the answer and why each option is right or wrong

Answer, C. {'a': 5, 'b': 9}

A. {'a': 5, 'b': 3}
Applies the squaring and summing correctly to group a but reports group b's own plain value instead of its square.
B. {'a': 3, 'b': 3}
Sums the plain values of each group instead of squaring them first.
C. {'a': 5, 'b': 9}
Correct. The lambda squares every value in a group before summing them, so group a becomes 1 squared plus 2 squared, 5, and group b becomes 3 squared alone, 9.
D. {'a': 9, 'b': 9}
Squares the already summed total of each group instead of squaring the individual values before adding them.

A custom function passed to agg() receives the whole group as a series and can do arbitrary computation on it before returning a single summary value. Whatever that function computes, sum of squares here, runs independently inside each group, exactly like a built in aggregation would.

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.