Skip to main contentSkip to solution

You want to generate a report showing the top customers based on the amount they spent in your store. Which sequence should you follow while writing the query?

A. groupby

B. aggregate for sum total

C. sort_values

D. picking the required head rows

Solution

✅ Correct Option: 1

A. groupby: group all purchase rows by customer.

B. aggregate for sum total: add up each customer's spending.

C. sort_values: sort the totals in descending order so the biggest spenders come first.

D. picking the required head rows: take the first N rows, which are the top customers.

In pandas this reads as df.groupby('customer')['amount'].sum().sort_values(ascending=False).head(5).


Options 3 and 4: taking head rows first returns arbitrary rows, since the totals are not yet calculated and sorted. Head must always come last.

Option 2: sums cannot be aggregated per customer before grouping.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question