Pivot Customer Card Spend Into Monthly Category Share of Wallet
Last updated: November 29, 2026
Quick Overview
In pandas, turn a long table of card purchases into one row per customer per month with spend in each merchant category and each category's share of that month's total.
Capital One
November 29, 20260
0
0 solved
In pandas, turn a long table of card purchases into one row per customer per month with spend in each merchant category and each category's share of that month's total.
Category spend shares are a staple feature at Capital One for card products like Savor, which rewards dining and entertainment. The reviewer checks pivot_table usage, fill values for missing categories, and row-wise normalization.
What the Interviewer Expects
- Filters out refunds and payments before aggregating
- Buckets dates into months with to_period or dt.to_period
- Uses pivot_table with sum and fill_value=0
- Normalizes each row by its total with div on axis 0
- Names output columns clearly so spend and share do not collide
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you handle a refund in a later month for an earlier purchase?
- How would you turn these shares into a single concentration score?
- How would you keep the column set stable when a new category appears next month?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
- Input:
customer_id, txn_date, category, amountwith purchases positive and refunds negative. - Output: one row per
(customer_id, month), columnsspend_<category>andshare_<category>. - I ex...
Approach
Filter to positive amounts, add a month period, pivot with aggfunc="sum" and fill_value=0, compute shares with spend.div(spend.sum(axis=1), axis=0), prefix both frames, and join....