Data Analyst Interview
Menu
Browse in your language. All mock interviews, preparation sessions and feedback are in English only.

Pandas Explode: Expand Lists Without Inflating Revenue

Python • Nested data

Pandas Explode: Expand Lists Without Inflating Revenue

Separate orders from their tags before building a dashboard from nested exports.

Why does revenue increase after Pandas explode?

Exploding a list creates a row for each element and repeats the other fields from that source row. An order with two tags therefore carries its full order revenue twice. Sum revenue from the original order-level table, and use a separate order-to-tag table for tag analysis. A new row count is not a new order count.

The official Pandas explode reference describes the expansion and notes that an empty list produces a row containing a missing value. That placeholder also matters when counting tags.

A US and UK store export

This original synthetic fixture has three orders totaling $250. Order 101 has two merchandising tags, order 102 has one, and order 103 has no tags. All amounts are already integer USD cents under an agreed reporting currency; the UK label does not imply that an amount is GBP. Currency conversion is outside this example.

import pandas as pd

orders = pd.DataFrame({
    "order_id": [101, 102, 103],
    "market": ["US", "UK", "US"],
    "revenue_cents": [12000, 8000, 5000],
    "tags": [["email", "sale"], ["email"], []],
})
assert orders["order_id"].is_unique
expanded = orders.explode("tags", ignore_index=True)
print(expanded.to_string(index=False))
 order_id market  revenue_cents  tags
      101     US          12000 email
      101     US          12000  sale
      102     UK           8000 email
      103     US           5000   NaN

The $120 overstatement

Adding the expanded revenue column gives 37,000 cents ($370), while the source total is 25,000 cents ($250). The difference is exactly order 101’s $120 repeated for its second tag. No additional purchase happened. The operation changed the table’s grain—the meaning of one row.

print(orders["revenue_cents"].sum() / 100)    # 250.0
print(expanded["revenue_cents"].sum() / 100)  # 370.0
print(len(expanded))                        # 4
print(expanded["order_id"].nunique())        # 3

ignore_index=True only gives the expanded rows a fresh index. It does not prevent repeated order values or establish a business key. Keep order_id even when you reset the index.

An empty list is not one tag

There are four expanded rows but only three nonmissing tag occurrences. Order 103’s empty list becomes a missing tag in a retained row. Counting all rows would incorrectly report four tags.

print(expanded["tags"].notna().sum())  # 3 tag occurrences
print(orders["order_id"].nunique())    # 3 orders

In this fixture, an empty list means “known to have no tags.” In a real export, a missing field may instead mean “not collected” or “failed to load.” Preserve an input-status field before expansion if the distinction matters. This example does not treat an unknown collection as a confirmed empty collection.

Keep the revenue table and tag relationship separate

order_totals = orders[["order_id", "market", "revenue_cents"]].copy()
order_tags = (
    expanded.loc[expanded["tags"].notna(), ["order_id", "tags"]]
    .drop_duplicates(["order_id", "tags"])
)
print(order_tags.groupby("tags")["order_id"].nunique())
print(order_totals["revenue_cents"].sum() / 100)

The tag table reports two distinct orders with email and one with sale. The order table still reports $250. Deduplicating the pair (order_id, tags) is intentional here because each tag represents membership: repeating the same tag on one order should not add another membership.

If repeated elements instead represent real occurrences—such as two scans of a product—do not deduplicate them without an occurrence-level identifier and business rule. First decide what the list means.

Can you report revenue by tag?

You can report “revenue of orders containing this tag” as an overlapping metric. Email is associated with $200 of orders and sale with $120. Their $320 sum exceeds total revenue because order 101 belongs to both groups, while the untagged $50 order belongs to neither. Label the metric clearly and do not present the sum of tag bars as total store revenue.

An additive allocation needs an explicit rule, such as dividing an order across its distinct tags and retaining an untagged category. That creates an allocated-revenue metric, not evidence that each tag caused that revenue. It also needs a rounding policy for indivisible cents. Avoid silently choosing an attribution model just to make a chart reconcile.

Why dropping duplicate order IDs is not a universal repair

Returning to one row per order can recover this fixture’s total because the original data has exactly one complete revenue value per order. Applied to an order-line export, the same step could discard genuine products or quantities. Summing distinct dollar values is also wrong: unrelated orders can legitimately have the same price.

Preserve the source order table and validate its key before expansion. If source IDs are only unique within a store, use the store and order ID together. If records are revisions, establish which version is authoritative before creating either table.

Checks before a dashboard refresh

  • Confirm the input grain and key: one row per order in this exercise.
  • Record the source count and total before expansion.
  • Distinguish expanded rows, nonmissing tag occurrences, and distinct orders.
  • Test an empty list and a multi-element list explicitly.
  • Keep revenue aggregation at its intended grain.
  • Document whether tag metrics overlap or use an allocation rule.

Validation: eight checks passed with Pandas 2.2.3, covering expanded rows, repeated revenue, source total, nonmissing tags, distinct orders, the empty-list placeholder, tag memberships, and preserved order revenue. The official reference was checked separately; the fixture was executed locally, not against a client data source.

Related exercises

For a different source of repeated values, see Pandas merge validation. For identity across regional systems, try UNION versus UNION ALL with regional sales. Continue with the Pandas learning guide.

Leave a Comment

✉ WhatsApp