Aggregation & reshaping — quiz
8 questions covering this module. groupby, sorting, merging and pivoting.
Which keeps the original row count?
- agg
- transform
- sum
- count
Answer: transform — transform aligns the result back onto every row, like a window function.
Why call reset_index() after groupby?
- To sort
- To turn the grouping key back into a normal column
- To remove nulls
- To save memory
Answer: To turn the grouping key back into a normal column — Otherwise it stays in the index and complicates plotting and merging.
df['x'].rank() on tied values gives, by default:
- Sequential integers
- The average rank, e.g. 2.5
- The lowest rank
- An error
Answer: The average rank, e.g. 2.5 — method="min" or "dense" match SQL behaviour.
The efficient way to get the top 10 rows by revenue:
- sort_values then head
- nlargest(10, "revenue")
- rank then filter
- groupby
Answer: nlargest(10, "revenue") — nlargest avoids sorting the whole frame.
A left merge increases the row count. This means:
- Normal behaviour
- The right table has duplicate keys
- Missing values
- Wrong how=
Answer: The right table has duplicate keys — Duplicate keys on the right fan the rows out.
Which argument raises an error if the relationship is not as expected?
- indicator
- validate
- suffixes
- how
Answer: validate — validate='many_to_one' checks the key relationship.
Which converts month columns into rows?
- pivot_table
- melt
- stack
- concat
Answer: melt — melt unpivots wide data into long form.
pivot_table differs from pivot because it:
- Is faster
- Aggregates duplicate entries rather than raising
- Only takes one column
- Requires a date index
Answer: Aggregates duplicate entries rather than raising — pivot raises when the index/column pair is not unique.