KatInterview

Revenue Rollups, a 2x2 Pivot and a VIP Flag in pandas

SQL & DataModel answer
MediumModel answerSQL & Datapandasmergegroupby

Last updated

Join two small tables in pandas, then build channel revenue totals, a member-by-channel pivot, per-state order and buyer counts, and a rule-based high-value flag.

You work with two pandas DataFrames from a messaging and commerce product. Write code that carries out four connected steps. The merged DataFrame from Step 1 is reused in every later step.

users

user_idis_memberstateage
1011CA29
1020NY41
1031CA35
1040TX50

orders

order_iduser_idchannelamountstatus
7001101SMS12.00delivered
7002102Email5.00delivered
7003103SMS7.00delivered
7004103Email4.00delivered
7005101Organic3.50delivered
7006104SMS6.00undelivered

Step 1: join and total revenue. Left-join orders to users on user_id. Using only status == "delivered" rows, produce two DataFrames from groupby(...).sum():

  • (a) revenue per channel
  • (b) revenue per channel for members only (is_member == 1)

Step 2: a 2x2 pivot. Using pivot_table with aggfunc="sum", build a table of delivered revenue with is_member (0 and 1) as rows and only the channels SMS and Email as columns. Missing cells must show 0.

Step 3: per-state counts. On the full merged frame (all statuses), compute for each state the number of orders (size) and the number of distinct purchasers (nunique of user_id). Return the two states with the most orders, using sort_values.

Step 4: a flag column. Add high_value_flag with np.where. It is 1 when either condition holds, otherwise 0:

  • the user's lifetime delivered amount is at least 15, or
  • the user has at least 2 delivered SMS orders.

Compute the per-user figures with earlier groupby results, and avoid SettingWithCopyWarning. Show the head of the final frame with the relevant columns.

Explain your choices briefly, including how you handle ties and users with no delivered orders.

Hints

Hint 1

Merge once, then create a single delivered-only frame with .copy() and reuse it for the revenue steps. Remember Step 3 uses all statuses, so it needs the unfiltered merged frame.

Hint 2

pivot_table orders columns alphabetically and drops combinations that never occur. Use fill_value=0 and then reindex to force index [0, 1] and columns ['SMS', 'Email'].

Hint 3

For the flag, compute per-user delivered totals and delivered-SMS counts with groupby, map them back onto the order rows, fillna(0) for users with no delivered orders, then apply np.where on whole columns. In Step 3, add a secondary sort key so the NY/TX tie is deterministic.