Revenue Rollups, a 2x2 Pivot and a VIP Flag in pandas
SQL & DataModel answerLast 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_id | is_member | state | age |
|---|---|---|---|
| 101 | 1 | CA | 29 |
| 102 | 0 | NY | 41 |
| 103 | 1 | CA | 35 |
| 104 | 0 | TX | 50 |
orders
| order_id | user_id | channel | amount | status |
|---|---|---|---|---|
| 7001 | 101 | SMS | 12.00 | delivered |
| 7002 | 102 | 5.00 | delivered | |
| 7003 | 103 | SMS | 7.00 | delivered |
| 7004 | 103 | 4.00 | delivered | |
| 7005 | 101 | Organic | 3.50 | delivered |
| 7006 | 104 | SMS | 6.00 | undelivered |
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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Build one order-level frame and derive everything from it. Each step is one filter plus one aggregation, and nothing is done row by row.
- Merge once. A left join keeps every order, and each row gains the user's attributes.
user_idis unique inusers, so the join is many-to-one. Passingvalidate="many_to_one"makes pandas raise an error if duplicate users ever appear. Otherwise they would silently multiply rows and inflate revenue. - Filter once. Make
delivered = merged[merged.status == "delivered"].copy()a single time. The.copy()means later assignments never triggerSettingWithCopyWarning. - Aggregate with the right tool. Use
groupby().sum()for totals,pivot_tablefor the grid, andgroupby().agg(...)with named aggregations for the state counts. - Label at user level, then broadcast. Compute per-user metrics with
groupby,mapthem onto the order rows, and finish withnp.whereon full columns.
Code
import numpy as np
import pandas as pd
users = pd.DataFrame({
"user_id": [101, 102, 103, 104],
"is_member": [1, 0, 1, 0],
"state": ["CA", "NY", "CA", "TX"],
"age": [29, 41, 35, 50],
})
orders = pd.DataFrame({
"order_id": [7001, 7002, 7003, 7004, 7005, 7006],
"user_id": [101, 102, 103, 103, 101, 104],
"channel": ["SMS", "Email", "SMS", "Email", "Organic", "SMS"],
"amount": [12.00, 5.00, 7.00, 4.00, 3.50, 6.00],
"status": ["delivered"] * 5 + ["undelivered"],
})
# Step 1
merged = orders.merge(users, on="user_id", how="left", validate="many_to_one")
delivered = merged[merged["status"] == "delivered"].copy()
total_by_channel = delivered.groupby("channel")[["amount"]].sum()
member_by_channel = (
delivered[delivered["is_member"] == 1].groupby("channel")[["amount"]].sum()
)
# Step 2
pivot = (
delivered[delivered["channel"].isin(["SMS", "Email"])]
.pivot_table(index="is_member", columns="channel", values="amount",
aggfunc="sum", fill_value=0)
.reindex(index=[0, 1], columns=["SMS", "Email"], fill_value=0)
)
# Step 3 (full merged frame, all statuses)
state_stats = (
merged.groupby("state")
.agg(total_orders=("order_id", "size"),
unique_purchasers=("user_id", "nunique"))
.reset_index()
.sort_values(["total_orders", "state"], ascending=[False, True])
)
top2 = state_stats.head(2)
# Step 4
lifetime = delivered.groupby("user_id")["amount"].sum()
sms_cnt = delivered[delivered["channel"] == "SMS"].groupby("user_id").size()
merged = merged.assign(
lifetime_delivered=merged["user_id"].map(lifetime).fillna(0.0),
delivered_sms_orders=merged["user_id"].map(sms_cnt).fillna(0).astype(int),
)
merged["high_value_flag"] = np.where(
(merged["lifetime_delivered"] >= 15) | (merged["delivered_sms_orders"] >= 2),
1, 0,
)
print(merged[["order_id", "user_id", "channel", "amount", "status",
"lifetime_delivered", "delivered_sms_orders",
"high_value_flag"]].head())
Expected results
- Step 1a (delivered revenue by channel): Email 9.0, Organic 3.5, SMS 19.0.
- Step 1b (members only): Email 4.0, Organic 3.5, SMS 19.0. Order 7002 belongs to non-member 102, so Email falls from 9 to 4.
- Step 2 (pivot):
| is_member | SMS | |
|---|---|---|
| 0 | 0 | 5 |
| 1 | 19 | 4 |
The non-member SMS cell is 0 because the only non-member SMS order (7006) is undelivered.
- Step 3: CA has 4 orders from 2 purchasers. NY and TX tie at 1 order each, and the secondary sort on
stateputs NY second.
| state | total_orders | unique_purchasers |
|---|---|---|
| CA | 4 | 2 |
| NY | 1 | 1 |
- Step 4: Lifetime delivered totals are 101 → 15.5, 102 → 5.0, 103 → 11.0, 104 → 0. Delivered SMS counts are 1 for users 101 and 103, and 0 otherwise. Only user 101 qualifies (15.5 ≥ 15). The flags for orders 7001 to 7006 are 1, 0, 0, 0, 1, 0.
Why these choices
- Left join with validation. Orders are never dropped and the row count stays at 6. The validation guards against silent fan-out.
- Reindexing the pivot.
pivot_tablesorts columns alphabetically and omits combinations with no data. Reindexing gives a stable 2x2 shape even if one group had no delivered orders. - Different filters per step. Revenue uses delivered orders only. The state counts use every order, so the undelivered TX order still counts. Mixing these up is the most common mistake here.
fillna(0)aftermap. User 104 has no delivered orders, somapreturns NaN. Without the fill, the metric columns show NaN and the comparison only works by accident.- Deterministic ties.
sort_valueson its own gives an arbitrary order for equal counts. A second key makes the output reproducible. sizeversuscount.sizecounts rows, whilecountskips NaN. For order totalssizeis the safer choice.
Complexity
Let n be the number of orders, u the number of users, and g the number of groups.
- The hash join costs O(n + u).
- Each groupby or pivot costs O(n), plus O(g log g) if the groups are sorted.
mapandnp.whereare O(n) and vectorized.- Space is O(n) for the merged and delivered frames, plus O(g) per aggregate.
Edge cases and trade-offs
- Orders with no matching user. The left join yields NaN in
is_memberandstate.groupbydrops NaN keys by default, so usedropna=Falseif an "unknown" bucket should be reported.is_memberalso becomes float, so cast it back after filling. - Messy categorical values. Real data may contain
"Delivered "or"sms". Normalize with.str.strip().str.lower()before filtering. - Money as floats. Threshold comparisons like
>= 15can misbehave with accumulated float error. Store cents as integers if exactness matters. value_countsshortcut.merged["state"].value_counts().head(2)gives order counts, but not unique purchasers, and it does not guarantee tie order. The explicitaggis better.- Chained assignment. Avoid
df[mask]["col"] = .... Use.copy(),.assign, or.loc. - Alternative for Step 4.
groupby().transform("sum")ondeliveredcomputes the same per-user metric, but it only covers users who have delivered rows. Amapplusfillnaonto the full frame is clearer for covering everyone.