Pivot Daily Ad Spend from Long to Wide by Placement

Last updated: November 29, 2026

Quick Overview

Given a long DataFrame of (date, campaign_id, placement, spend) where placement is one of Feed, Stories, Reels or Audience Network, reshape it to one row per date and campaign with a spend column per placement plus a total, filling missing placements with zero.

Meta
Data Manipulation (SQL/Python)
Data Scientist
Meta
November 29, 2026
Data Scientist
Technical Screen
Data Manipulation (SQL/Python)
Easy

0

0

0 solved


Given a long DataFrame of (date, campaign_id, placement, spend) where placement is one of Feed, Stories, Reels or Audience Network, reshape it to one row per date and campaign with a spend column per placement plus a total, filling missing placements with zero.

A typical warm-up in a Meta data science technical screen run in a shared Python notebook, framed around Ads Manager reporting where spend is logged per placement. The interviewer checks that you know pivot_table versus pivot, handle duplicate keys and missing combinations deliberately, and keep column order stable for a report.

What the Interviewer Expects
  • Use pivot_table with an explicit aggfunc so duplicate log rows are summed rather than raising
  • Fill missing placement cells with 0 instead of leaving NaN
  • Guarantee every placement column exists even if absent from the data
  • Add a total column and flatten the index back to ordinary columns
  • Explain why pivot would fail on duplicate (date, campaign, placement) rows
Key Topics to Cover
pivot_table
reshaping
fill_value
reindex columns
Ads reporting
How to Approach This
  1. Clarify the schema and expected output format before writing queries.
  2. Use CTEs (WITH clauses) to break complex queries into readable steps.
  3. Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
  4. Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
  5. For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
  • How would you produce the share of spend per placement instead of raw dollars?
  • How would you reverse this back to long format for a plotting library?
  • What changes if the data does not fit in memory and you must do this in SQL?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice SQL Problems
Sample Answer
Clarify the Data

Input spend has columns date, campaign_id, placement, spend. The logging layer can emit more than one row for the same key (for example, late corrections), so the same (date, campaign_id, pl...

Approach

pivot_table(index=[date, campaign_id], columns=placement, values=spend, aggfunc='sum', fill_value=0) handles both duplicates and missing cells. Then reindex(columns=PLACEMENTS, fill_value=0) adds ...


Submit Your Answer
Markdown supported