Interview Q&A / Data Science

BeginnerQuick answer1 min readUpdated 3 Oct 2026

When would you use pivot_table instead of groupby in pandas?

SHORT ANSWER

pivot_table is groupby with the second key spread across columns, giving a cross-tab style summary. Use it when you want a grid for reading or charting, and groupby when you want a long list of groups.

Explain it simply

A groupby with two keys gives a long list: one line per city and month. A pivot table lays the same numbers out as a grid, cities down the side and months across the top, just like an Excel pivot table.

Example

python
import pandas as pd
s = pd.DataFrame({
    "city": ["Pune", "Pune", "Delhi", "Delhi"],
    "month": ["Jan", "Feb", "Jan", "Feb"],
    "sales": [10, 20, 30, 40],
})
p = s.pivot_table(index="city", columns="month", values="sales", aggfunc="sum")
print(p)
# month  Feb  Jan
# city
# Delhi   40   30
# Pune    20   10

Columns come out alphabetically (Feb before Jan), so convert month to an ordered category if you want calendar order.

Handy options:

  • fill_value=0 fills combinations that never occurred.
  • margins=True adds row and column totals.
  • pivot (without table) only reshapes and fails on duplicate index and column pairs, while pivot_table aggregates duplicates.

What to say in the interview

"pivot_table is a groupby plus a reshape. I use it for a readable grid or a heatmap and groupby for pipelines. Unlike pivot, it handles duplicates by aggregating them, and I can add margins and fill_value for totals and gaps."

Common mistakes

  • Using pivot on data with repeated key pairs and getting a ValueError.

#pandas#pivot-table#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.