Interview Q&A / Data Science

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How does groupby work in pandas?

SHORT ANSWER

groupby splits the rows into groups by key, applies a function such as sum or count to each group, and combines the results into a new object. Named aggregation lets you compute several summaries in one call.

Explain it simply

Imagine a pile of UPI receipts. You sort them into piles by city, add up each pile, and write the totals on a sheet. That is groupby: split into piles, apply a calculation to each, combine into a table.

Example

python
import pandas as pd
df = pd.DataFrame({
    "city": ["Pune", "Pune", "Delhi", "Delhi", "Delhi"],
    "amount": [100, 300, 200, 400, 600],
})
print(df.groupby("city")["amount"].sum().to_dict())  # {'Delhi': 1200, 'Pune': 400}

out = df.groupby("city").agg(total=("amount", "sum"), orders=("amount", "count"))
print(out)
#        total  orders
# city
# Delhi   1200       3
# Pune     400       2

Notes:

  • Group keys become the index and are sorted by default. Use as_index=False or .reset_index() to get a normal column back.
  • agg(name=(column, function)) is the cleanest way to label results.
  • size() counts all rows per group, while count() ignores missing values.

What to say in the interview

"groupby follows split-apply-combine. I choose the key columns, then aggregate with sum, mean, count or several functions through agg. I use reset_index to flatten the result and know that count skips NaN while size does not."

Common mistakes

  • Forgetting that the grouping column becomes the index.
  • Using count when you wanted the number of rows including missing values.

#pandas#groupby#python

Related questions

Practise more Data Science questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Science quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.