All sample questions / pandas
What does print(df.groupby('k')['v'].sum().index.tolist()) print? pandas GroupBy and Aggregation
Block 4, GroupBy and Aggregation, question 9 of the pandas sample
import pandas as pd
df = pd.DataFrame({'k': ['b', 'a', 'b', 'a'], 'v': [1, 2, 3, 4]})
print(df.groupby('k')['v'].sum().index.tolist())
What does this print?
Show the answer and why each option is right or wrong
Answer, C. ['a', 'b']
- A. ['b', 'a']
- Assumes the groups keep the order in which their keys first appeared in the original data.
- B. [0, 1]
- Assumes the index of the aggregated result is a plain positional range instead of the sorted group keys.
- C. ['a', 'b']
- Correct. groupby sorts its group keys in ascending order by default, so even though b appears first in the data, a comes first in the result.
- D. ['a', 'a', 'b', 'b']
- Assumes the index repeats each key once per original row instead of collapsing to one entry per group.
The default sort=True makes groupby order its result by the group keys themselves, regardless of the order those keys first showed up in the source data. This sorting is a separate step from the aggregation and happens the same way for any aggregation function.
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.