Skip to content
tezvyn:

Calculate total and average sales per region in pandas

Source: pandas.pydata.orgMediumHow cards are made

Calculate total and average sales per region in pandas

Tests split-apply-combine fluency. A strong answer groups by Region then calls agg with a dict or named aggregation to return sum and mean of Sales_Amount together. Red flag: chaining separate groupby calls or looping rows manually.

What's really being asked

The interviewer wants to see if you understand pandas groupby aggregation beyond simple single-statistic summaries. Specifically, they are checking whether you know how to compute multiple aggregates on the same column in a single expression without resorting to iterative or multi-pass approaches. At the senior level, this reveals fluency with the split-apply-combine paradigm, awareness of API ergonomics, and understanding that vectorized operations outperform Python-level loops. They also care whether you can produce readable, maintainable code that colleagues can immediately understand.

The full answer

First, mention grouping by Region using df.groupby("Region"). Second, specify selecting the Sales_Amount column to avoid unnecessary computations on other columns. Third, call the agg method with either a dictionary mapping the column to a list of functions like {"Sales_Amount": ["sum", "mean"]} or use named aggregation via .agg(total_sales=("Sales_Amount", "sum"), avg_sales=("Sales_Amount", "mean")). Fourth, note that this returns a DataFrame indexed by Region with both columns produced in one vectorized pass through the data. Optionally mention that named aggregation yields cleaner column names than the default MultiIndex columns produced by the dictionary approach, which saves a cleanup step.

The mistakes people make

A red flag is proposing two separate groupby operations, such as df.groupby("Region")["Sales_Amount"].sum() followed by a second call for mean, then merging the results manually. Another red flag is using apply with a custom lambda that returns a Series, which is far slower than the built-in aggregation engine and harder to read. Iterating over rows or groups with a for loop is also unacceptable at this level because it abandons vectorization entirely and consumes far more memory. Finally, grouping the entire DataFrame without column selection first is not wrong but shows less precision, since it can trigger unnecessary computation on irrelevant columns or unexpected type issues.

What usually comes next

The interviewer might ask how you would rename the resulting columns cleanly, which is a natural segue into named aggregation or post-hoc column flattening. They might ask how to handle missing values, prompting a discussion of whether to pass skipna behavior or pre-filter the data. Another follow-up could involve adding Product_Category to the groupby keys, testing whether you understand multi-index grouping and hierarchical aggregation. A performance-oriented follow-up might contrast agg with apply or ask how the operation scales to datasets that do not fit in memory, moving toward Dask or Polars.

A concrete example

Suppose the DataFrame is named sales. The concise expression is sales.groupby("Region")["Sales_Amount"].agg(total="sum", average="mean"). This groups by Region, isolates Sales_Amount, and computes both sum and mean in one call, returning a DataFrame with columns total and average and an index of unique regions. If you prefer the dictionary syntax, sales.groupby("Region")["Sales_Amount"].agg({"Sales_Amount": ["sum", "mean"]}) works but creates a MultiIndex column that often requires cleanup afterward. For a senior candidate, recommending the named aggregation version demonstrates modern pandas best practices.

Interview question

Which single expression best computes total and average Sales_Amount per Region in pandas?

  • a.Apply a lambda that returns a Series with sum and mean for each group
  • b.Select Sales_Amount after groupby and use agg with named aggregationsCorrect
  • c.Chain two separate groupby operations for sum and mean, then join the results
  • d.Loop through Region groups with a for-loop and accumulate sums and counts manually
Why?

Selecting the column and using named aggregation computes both statistics in a single vectorized pass with clean column names. Option C is a common anti-pattern that runs two separate groupby passes and requires manual merging, which is slower and harder to maintain.

Just read this? Test yourself on what you have been reading.

Read the original → pandas.pydata.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.

See open roles