Course outline

pandas / Intermediate: grouping, joins and temporal quality / Lesson 14

Explode and Changing Row Grain

Expand list-valued cells while preserving order-level totals and understanding empty or repeated items.

About 23 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Identify grain before and after explode.
  • Avoid summing repeated order-level values.
  • Test empty lists, duplicates, and index handling.
  • Explain how explode changes parent and child grain and repeats parent fields.
  • Reconcile actual child occurrences, empty lists and order-level totals.

Define the row before expanding

A list-valued column can store multiple items in one order row. Exploding it creates rows for individual items while other columns are repeated. The resulting table has a different grain, so a repeated order total is no longer additive across its rows. State the unit of each field before aggregating.

Retain a stable order identifier and decide how to handle empty lists, missing values, and repeated items. A repeated item may mean two purchased units or a duplicate entry; the correct interpretation comes from the source contract rather than the reshape operation.

Expand a synthetic order table

In a local lab with pandas installed, this example explodes a list of items and resets the output index. Order a becomes two item rows, each carrying the same order-level total. The example is illustrative and is not executed by the public reader; check the installed version’s behavior for your data.

python Expand list-valued items
import pandas as pd

orders = pd.DataFrame({"order": ["a", "b"], "items": [["pen", "book"], ["pen"]], "total": [30, 10]})
items = orders.explode("items", ignore_index=True)
print(items)

The two original order rows become three item rows, and the total for order a is repeated.

Calculate at the correct grain

Calculate revenue from the original order table or from a separately validated one-row-per-order table. Do not sum the repeated total in the exploded table: that would count order a twice. The second lab compares the original order total and the number of distinct order identifiers after expansion.

python Keep order-level controls
import pandas as pd

orders = pd.DataFrame({"order": ["a", "b"], "items": [["pen", "book"], ["pen"]], "total": [30, 10]})
items = orders.explode("items", ignore_index=True)
print("order total", orders["total"].sum())
print("distinct orders", items["order"].nunique())

The source totals sum to 40 and the exploded table retains two distinct order identifiers.

Inspect edge cases

Test an empty list, a missing value, and a list containing the same item twice, using the installed version’s documented behavior. Decide whether each resulting row represents an actual item. If exploding multiple related columns together, their list lengths must meet the method’s requirements and corresponding positions must describe the same item.

Reconcile the reshaped data

Compare source order counts, expected item counts, missing items, and order-level totals before and after expansion. Inspect one order with multiple items and one empty order. Preserve source provenance and explain any exclusions so that an analyst can trace an item row back to its original record.

Separate parent and child grain

A list-valued field can represent several child occurrences inside one parent row. Exploding an order’s items turns one order row into item-occurrence rows and repeats the other parent fields. State which fields belong to the order, which belong to an item occurrence, and which are additive at each grain. If an order total is repeated on each child row, summing that column after expansion counts the same order more than once. Compute revenue on the validated one-row-per-order source, or construct and validate a unique parent table before summing.

A repeated item name within a list is not automatically a duplicate event. It might represent two purchased units or an accidental repeated entry. Keep the order ID and, when individual positions matter, a source occurrence position so two identical names can remain distinguishable. A new sequential index from ignore_index=True is convenient for display but does not establish a valid parent or child business key. Validate parent identity before expansion and child identity according to the source contract afterward.

Understand empty, missing and scalar inputs

For a nonempty list, explode creates one row per element. Under the documented pandas behavior, an empty list produces a row whose exploded value is missing; a scalar is left as a scalar in one row. A missing scalar likewise remains a missing child value. These output rows are not automatically actual child occurrences. Preserve a source-side indicator that distinguishes an empty list from an unknown list if their business meanings differ, because both can result in a missing-looking expanded value.

If the contract requires a list in every parent row, validate that input type and reject unexpected scalars before exploding rather than accepting the API’s permissive behavior as business validity. Count expected actual children from the source lists, count empty and unknown parents separately, and compare those with the expanded result. Filtering missing child values can be appropriate, but record which parents were removed and why; otherwise an empty order may disappear from a later coverage report.

Expand related columns only when positions agree

DataFrame.explode can expand multiple list-valued columns together. For each row, the selected list-like columns must have matching lengths. A pair of lists such as items=[pen,book] and quantities=[2,1] represents positional pairs pen/2 and book/1 only if the source contract guarantees that alignment. pandas can check length compatibility, but it cannot prove that the nth quantity belongs to the nth item. Validate the meaning and units of each paired field, and reject or reconcile mismatched lengths before accepting the output.

Exploding columns independently can create an unintended Cartesian product or misaligned associations if the results are recombined carelessly. Build an explicit child position within each parent when it is needed to preserve the source sequence, and verify the resulting parent-position pairs are unique. If an input is a set, iteration order is not a deterministic business sequence; avoid using it to attach positional quantities. Use ordered source structures when position is part of the identity contract.

Trace a synthetic order and item audit

The program below uses three synthetic orders: A has pen and book, B has pen, and C has an empty item list. Their order totals are 30, 10 and 0. explode produces four rows because the empty list produces one missing-value placeholder. Only three rows contain actual listed items; order C remains visible as a parent with no listed child. The original order totals sum to 40, whereas summing the repeated expanded totals gives 70 because A’s total is copied onto two child rows.

The example records the source list length before expansion and verifies both the actual child count and the set of parent IDs. It does not decide that every empty order is valid or that a missing child represents a zero-valued purchase. A real acceptance rule may reject C or retain it for review. Compare source order totals on the parent table, not the repeated child table, and preserve the order ID and source evidence for each disposition.

python Synthetic order expansion audit
import pandas as pd

orders = pd.DataFrame({'order':['A','B','C'], 'items':[['pen','book'],['pen'],[]], 'total':[30,10,0]})
assert orders['order'].is_unique
orders['source_count'] = orders['items'].map(len)
expanded = orders.explode('items', ignore_index=True)
assert len(expanded) == 4 and expanded['items'].notna().sum() == 3
assert set(expanded['order']) == set(orders['order'])
print(len(expanded), expanded['items'].notna().sum(), orders['total'].sum(), expanded['total'].sum())
Expected output
4 3 40 70

Four expanded rows include three items and one empty-list placeholder; parent revenue is 40, while repeated child totals sum to 70. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Reconcile shape, identity and measures

A useful expansion audit compares source parent count, unique parent keys, source list lengths, actual nonmissing child count, empty and unknown list counts, and parent IDs present after filtering. Check child keys and positional relationships independently of row count. For a reconstruction test, group child occurrences by parent in their original order and compare the ordered lists, including repeated items; sorting or deduplicating can change the meaning even if the set of item names stays the same.

Test a nonempty list, an empty list, a missing value, an unexpected scalar, a repeated item and unequal paired lists. Verify which output rows are placeholders and which are actual children. A matching order total does not prove item completeness, and a matching child count does not prove correct item-to-quantity pairing. The selected course baseline is pandas 3.1.0; official explode references consulted during authoring identified themselves as 3.1.1. Standalone examples are qualified separately on isolated synthetic inputs with exact Python, pandas and NumPy versions recorded. These standalone programs were executed in that isolated environment.

20 worked examples

1. Expand an item list

Problem: Explode one order with two listed items.

  1. The source list contains pen and book.
  2. Explode creates one row for each listed occurrence.
python Expand an item list
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':[['pen','book']]})
r = f.explode('items', ignore_index=True)
print(r['items'].tolist(), len(r))
Expected output
['pen', 'book'] 2

The output grain changes from order to item occurrence. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: The output grain changes from order to item occurrence.

2. Repeated order total

Problem: Compare parent and exploded sums for one two-item order.

  1. The parent order has one total of 30.
  2. The expanded two rows each repeat 30, producing an inflated sum of 60.
python Repeated order total
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':[['pen','book']], 'total':[30]})
r = f.explode('items')
print(f['total'].sum(), r['total'].sum())
Expected output
30 60

An order-level measure is not additive across repeated child rows. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: An order-level measure is not additive across repeated child rows.

3. Empty list placeholder

Problem: Inspect the expanded result for an empty item list.

  1. The source list contains no actual items.
  2. The expanded result retains one row with a missing item value.
python Empty list placeholder
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':[[]]})
r = f.explode('items')
print(len(r), r['items'].isna().tolist())
Expected output
1 [True]

The placeholder row should not automatically be counted as an item. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: The placeholder row should not automatically be counted as an item.

4. Missing scalar input

Problem: Inspect an order whose item field is missing.

  1. The source field is a missing scalar rather than a list.
  2. Explode retains one row whose item value remains missing.
python Missing scalar input
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':[None]})
r = f.explode('items')
print(len(r), r['items'].isna().tolist())
Expected output
1 [True]

A missing list and an empty list need source-side distinction if their meanings differ. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: A missing list and an empty list need source-side distinction if their meanings differ.

5. Scalar remains scalar

Problem: Inspect an unexpected scalar item passed to explode.

  1. The field is the scalar string pen, not a list.
  2. Explode leaves it in one row without splitting its characters.
python Scalar remains scalar
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':['pen']})
r = f.explode('items')
print(len(r), r.loc[0,'items'])
Expected output
1 pen

API acceptance does not prove that a scalar meets a list-only source contract. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: API acceptance does not prove that a scalar meets a list-only source contract.

6. Repeated listed item

Problem: Preserve two identical item occurrences in a list.

  1. The list contains pen twice in two positions.
  2. Explode returns both occurrences without deciding whether they are legitimate.
python Repeated listed item
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':[['pen','pen']]})
r = f.explode('items', ignore_index=True)
print(r['items'].tolist())
Expected output
['pen', 'pen']

The source contract determines whether repeated items mean multiple units or an error. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: The source contract determines whether repeated items mean multiple units or an error.

7. Retain source index

Problem: Observe repeated index labels after exploding one source row.

  1. Both item rows come from the source label row1.
  2. The default explode result repeats that index label.
python Retain source index
import pandas as pd

f = pd.DataFrame({'items':[['pen','book']]}, index=['row1'])
r = f.explode('items')
print(r.index.tolist())
Expected output
['row1', 'row1']

A repeated source index traces origin but does not uniquely identify children. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: A repeated source index traces origin but does not uniquely identify children.

8. New positional index

Problem: Reset the exploded axis while retaining the order field.

  1. The two expanded items receive positions 0 and 1.
  2. The order field remains A on both rows.
python New positional index
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':[['pen','book']]}, index=['row1'])
r = f.explode('items', ignore_index=True)
print(r.index.tolist(), r['order'].tolist())
Expected output
[0, 1] ['A', 'A']

The new index does not replace the parent business identity. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: The new index does not replace the parent business identity.

9. Occurrence positions

Problem: Attach list positions before expanding repeated items.

  1. The two equal names have source positions 0 and 1.
  2. Joint expansion keeps each position with its corresponding occurrence.
python Occurrence positions
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':[['pen','pen']], 'pos':[[0,1]]})
r = f.explode(['items','pos'], ignore_index=True)
print(list(zip(r['order'],r['pos'])))
Expected output
[('A', 0), ('A', 1)]

Parent and position together can identify list occurrences under that contract. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: Parent and position together can identify list occurrences under that contract.

10. Expand paired lists

Problem: Expand aligned items and quantities together.

  1. The first item and quantity are pen and 2.
  2. The second pair is book and 1, retained by joint expansion.
python Expand paired lists
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':[['pen','book']], 'qty':[[2,1]]})
r = f.explode(['items','qty'], ignore_index=True)
print(list(zip(r['items'],r['qty'])))
Expected output
[('pen', 2), ('book', 1)]

Equal list lengths permit position-by-position expansion. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: Equal list lengths permit position-by-position expansion.

11. Mismatched list lengths

Problem: Catch unequal lengths when exploding two columns together.

  1. The items list has two elements and the quantity list has one.
  2. Joint explode raises ValueError for the unequal row lengths.
python Mismatched list lengths
import pandas as pd

f = pd.DataFrame({'items':[['pen','book']], 'qty':[[2]]})
try:
    f.explode(['items','qty'])
except ValueError:
    print('length mismatch')
Expected output
length mismatch

The source pairing must be repaired or rejected before expansion. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: The source pairing must be repaired or rejected before expansion.

12. Parent identity check

Problem: Validate order IDs before expanding item lists.

  1. Both order IDs are present.
  2. A and B are distinct, satisfying this parent-key contract.
python Parent identity check
import pandas as pd

f = pd.DataFrame({'order':['A','B'], 'items':[['pen'],['book']]})
print(f['order'].notna().all(), f['order'].is_unique)
Expected output
True True

A parent-key check precedes child-grain interpretation. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: A parent-key check precedes child-grain interpretation.

13. Expected children and placeholders

Problem: Compare source list lengths with expanded and nonmissing rows.

  1. The source lists contain two actual elements in total.
  2. Expansion has three rows because the empty list contributes one missing placeholder.
python Expected children and placeholders
import pandas as pd

f = pd.DataFrame({'order':['A','B'], 'items':[['pen','book'],[]]})
r = f.explode('items')
print(sum(map(len,f['items'])), len(r), r['items'].notna().sum())
Expected output
2 3 2

List lengths and nonmissing child counts can be reconciled separately from output rows. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: List lengths and nonmissing child counts can be reconciled separately from output rows.

14. Filter actual children

Problem: Retain only nonmissing expanded items and report their parents.

  1. A produces the actual child pen.
  2. B has only a missing placeholder and disappears from the filtered child table.
python Filter actual children
import pandas as pd

f = pd.DataFrame({'order':['A','B'], 'items':[['pen'],[]]})
r = f.explode('items')
actual = r.loc[r['items'].notna()]
print(actual['order'].tolist(), sorted(set(f['order']) - set(actual['order'])))
Expected output
['A'] ['B']

Comparing parent sets reveals which parent has no retained child. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: Comparing parent sets reveals which parent has no retained child.

15. Reconstruct ordered list

Problem: Rebuild an order’s item sequence after explosion.

  1. The three expanded rows preserve the original list order in this fixture.
  2. Grouping them back into a list retains both pen occurrences.
python Reconstruct ordered list
import pandas as pd

f = pd.DataFrame({'order':['A'], 'items':[['pen','book','pen']]})
r = f.explode('items', ignore_index=True)
print(r.groupby('order', sort=False)['items'].agg(list).loc['A'])
Expected output
['pen', 'book', 'pen']

An ordered list comparison checks more than an unordered set of names. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: An ordered list comparison checks more than an unordered set of names.

16. Child count by parent

Problem: Count nonmissing children for two nonempty orders.

  1. A expands to two known item rows.
  2. B expands to one known item row.
python Child count by parent
import pandas as pd

f = pd.DataFrame({'order':['A','B'], 'items':[['pen','book'],['pen']]})
r = f.explode('items')
print(r.groupby('order')['items'].count().to_dict())
Expected output
{'A': 2, 'B': 1}

Counting nonmissing items describes child coverage at each parent. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: Counting nonmissing items describes child coverage at each parent.

17. Same item in two orders

Problem: Keep identical item names associated with separate parents.

  1. Each order contains one pen occurrence.
  2. The two occurrences belong to different order IDs.
python Same item in two orders
import pandas as pd

f = pd.DataFrame({'order':['A','B'], 'items':[['pen'],['pen']]})
r = f.explode('items', ignore_index=True)
print(list(zip(r['order'],r['items'])))
Expected output
[('A', 'pen'), ('B', 'pen')]

The parent ID is part of child identity across orders. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: The parent ID is part of child identity across orders.

18. Reject duplicate parent keys

Problem: Reject duplicate order IDs before calculating parent revenue.

  1. Both source rows have order ID A but report different totals.
  2. The one-row-per-order contract fails, so no parent revenue is accepted.
python Reject duplicate parent keys
import pandas as pd

f = pd.DataFrame({'order':['A','A'], 'items':[['pen'],['book']], 'total':[30,35]})
duplicate = f.loc[f.duplicated('order',keep=False),'order'].unique().tolist()
print(duplicate)
Expected output
['A']

A duplicate parent key requires reconciliation before a revenue sum. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: A duplicate parent key requires reconciliation before a revenue sum.

19. Retain list state

Problem: Distinguish empty and unknown source lists before expansion.

  1. The source explicitly marks A empty and B unknown.
  2. Both expanded item values are missing-looking, but the state remains different.
python Retain list state
import pandas as pd

f = pd.DataFrame({'order':['A','B'], 'items':[[],None]})
f['state'] = ['empty','unknown']
r = f.explode('items')
print(r['state'].tolist(), r['items'].isna().tolist())
Expected output
['empty', 'unknown'] [True, True]

A source-side flag preserves a distinction that the expanded values alone cannot show. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: A source-side flag preserves a distinction that the expanded values alone cannot show.

20. Complete expansion audit

Problem: Reconcile parent totals and actual item count with an empty list.

  1. Three parent orders expand to four rows, including C’s placeholder.
  2. Three actual items are present and source order totals sum to 40.
python Complete expansion audit
import pandas as pd

f = pd.DataFrame({'order':['A','B','C'], 'items':[['pen','book'],['pen'],[]], 'total':[30,10,0]})
r = f.explode('items', ignore_index=True)
print(len(f), len(r), r['items'].notna().sum(), f['total'].sum())
Expected output
3 4 3 40

Parent and child invariants are checked at their respective grains. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.

Why this result follows: Parent and child invariants are checked at their respective grains.

Common errors and fixes

Revenue increases after explode.

Why it happens
An order-level total was repeated and summed once per item.
How to fix it
Compute revenue at validated order grain.
Prevent it next time
Document field grain and reconcile control totals.

An empty list is counted as a purchased item.

Why it happens
The resulting missing value was treated as an item.
How to fix it
Apply the documented empty-list policy before item counts.
Prevent it next time
Include empty and missing list fixtures.

Item attributes no longer correspond after expansion.

Why it happens
Related lists had incompatible lengths or positions.
How to fix it
Validate paired lists and repair the source representation.
Prevent it next time
Store and test item attributes as a coherent record.

20 practice exercises

1. Order a has two items and total 30; order b has one item and total 10. What is revenue?

Show hint

Sum once per order, not once per exploded item.

Show worked solution

Revenue is 40 at order grain. Summing the repeated exploded totals would give 70 and double-count order a.

Order a contributes 30 once and order b contributes 10 once, so revenue is 40. Exploding repeats a’s 30 on two item rows, and summing those repeated totals gives 30+30+10=70, which double-counts a.

Check your solution

  • Parent-grain revenue is 40.
  • The naive exploded sum is 70.

2. A list contains the same item twice. Can you deduplicate it automatically?

Show hint

Ask what a repeated list position represents in the source.

Show worked solution

Not without the source definition. It could represent two units or a duplicate record. Check the business rule and retain evidence of the decision.

Two identical item names may represent two purchased units or a repeated entry. Preserve the original list and occurrence positions, and consult the source contract before removing either occurrence.

Check your solution

  • Both source occurrences remain available for review.
  • A deduplication decision requires a documented business rule.

3. Order A lists three items and B lists two. Predict exploded row count and verify the parent IDs.

Show hint

Each nonempty list contributes one row per element.

Show worked solution

A contributes three rows and B contributes two, for five expanded rows. The parent IDs should occur three and two times respectively; check the actual item occurrences as well as the count.

Check your solution

  • Expanded row count is 5.
  • A appears 3 times and B appears 2 times.

4. Order A has three items and total 12; B has one item and total 8. Compare parent revenue with a naive exploded sum. A separate refund of 3 belongs to order B; calculate net parent revenue while preserving the original gross total.

Show hint

The first order total repeats once per child.

Show worked solution

Parent revenue is 12+8=20. Exploded rows repeat A’s total three times, giving 3×12+8=44; use the parent-grain total and investigate any downstream report that sums the repeated field. Gross parent revenue remains 20; subtracting the approved B refund gives net revenue 17. Do not apply the refund once per child.

Check your solution

  • Correct parent revenue is 20.
  • Naive expanded sum is 44.
  • Net parent revenue is 17 after one refund.

5. Compare order A with empty list [] and order B with list [None]. After explode both have a missing-looking item. State what source list lengths establish and what remains unknown.

Show hint

The missing placeholder is not automatically an item.

Show worked solution

A has a known empty list with length 0; B has one listed position whose value is missing. Both yield a missing-looking row, but B’s child value is unknown rather than proof of no child. Preserve the source state and apply an explicit acceptance policy.

Check your solution

  • A has zero listed positions.
  • B has one position with an unknown value.

6. Order A has [] and B has None. Both expanded values look missing. Design a source-state distinction. The acceptance rule permits empty lists but rejects unknown lists; identify each disposition.

Show hint

Record the difference before expanding.

Show worked solution

Mark A as empty-list and B as unknown before explode. The output may show missing item values for both, but the state field preserves the different reasons; report them separately and apply the appropriate acceptance policy. Accept A as a known empty parent and reject or hold B as unknown, retaining both IDs and reasons.

Check your solution

  • A is known empty.
  • B has an unknown list.
  • A is accepted as empty; B is held as unknown.

7. A source contract requires items to be lists, but order A contains scalar "pen". Should its successful explode result be accepted? If the producer later confirms the scalar is shorthand for a one-item list, specify the explicit repair and resulting count.

Show hint

API behavior and source validation are separate.

Show worked solution

No. explode can leave the scalar pen in one row, but that does not satisfy the list-only input contract. Flag A for source correction or a documented normalization rule before counting its output as an accepted child. Normalize A to ["pen"] under that approved rule, record the conversion, and then expect one actual child.

Check your solution

  • The scalar remains one value under explode.
  • The list-only contract fails for A.
  • The approved repaired list contains one pen occurrence.

8. Order A lists [pen,pen]. Preserve both occurrences and assign source positions. Quantities [1,2] correspond to the two positions; determine total units without collapsing either occurrence.

Show hint

Use the list positions as part of an occurrence key.

Show worked solution

Retain the two entries with positions 0 and 1, giving keys (A,0) and (A,1). They may represent two units under the source contract; do not deduplicate the names without a business rule. Pair positions with quantities 1 and 2 and sum them to 3 units while retaining both child keys.

Check your solution

  • Both pen occurrences remain.
  • Their parent-position keys differ.
  • The two occurrences contribute 3 units in total.

9. Source index row1 contains order A with two items. After explode, is row1 a unique child key? A second source row also has label row1 but order B; explain why the index cannot even uniquely identify parents.

Show hint

The source index repeats on each expanded row.

Show worked solution

No. Both child rows inherit row1 under the default index behavior. Preserve order A and add occurrence positions or another source child identifier; source-row provenance and child uniqueness are different needs. The same label refers to source rows for A and B, so retain a unique source row ID and order ID before expansion.

Check your solution

  • row1 appears twice.
  • A child key needs an additional distinguishing field.
  • Duplicate row1 labels obscure two distinct parents.

10. After ignore_index=True, expanded rows have positions 0,1 but both represent order A and item pen. Does index uniqueness validate child identity?

Show hint

A generated position is not necessarily a stable business key.

Show worked solution

No. The index positions are unique for this result, but the two identical item values could be valid occurrences or a source duplicate. Compare the source list and its occurrence contract, and preserve parent and source positions when needed.

Check your solution

  • The generated index is unique.
  • The business interpretation of the two pen occurrences remains unresolved.

11. Order A has items [pen,book] at source positions [0,1]. Construct child keys. A manifest also expects position 2; report the gap.

Show hint

Combine parent ID with occurrence position.

Show worked solution

The actual child keys are (A,0) and (A,1), which are unique. The independently expected (A,2) is absent, so uniqueness does not establish complete child coverage. Reconcile the missing occurrence before accepting the order.

Check your solution

  • Actual composite keys are (A,0),(A,1).
  • Expected child key (A,2) is absent.

12. Order A has items [pen,book] and quantities [2,3]. Pair them and compute total item units.

Show hint

Expand the lists together by position.

Show worked solution

The paired rows are pen/2 and book/3, and total item units are 5. Check equal lengths before expansion and validate that the source defines positional pairing; equal length alone cannot prove semantic correctness.

Check your solution

  • Pairs are (pen,2) and (book,3).
  • The quantity sum is 5.

13. Order A has two items but one quantity; B has one item and one quantity. Identify the invalid parent before joint explode.

Show hint

Compare list lengths per parent row.

Show worked solution

A has lengths 2 and 1 and must be rejected or repaired; B has matching lengths 1 and 1. Report A’s order ID and retain the original lists rather than padding a quantity without a source rule.

Check your solution

  • A has a length mismatch.
  • B has matching list lengths.

14. Two source rows share order ID A and contain different item lists. Should expansion proceed under a one-row-per-order contract?

Show hint

Validate parent uniqueness before creating child rows.

Show worked solution

No. Duplicate A violates the declared parent grain and could duplicate order-level totals. Hold both source rows, determine whether they are revisions or separate orders, and establish a correct parent key before expansion.

Check your solution

  • The parent ID A is duplicated.
  • No survivor is selected without a business rule.

15. Order A lists [pen,book] and B lists []. Reconcile source child count with exploded rows. Order B has total 7; determine whether filtering missing children before calculating revenue is safe.

Show hint

Empty lists produce a missing placeholder row.

Show worked solution

The source contains two actual children. explode yields three rows: two for A and one missing placeholder for B. Count two nonmissing items and separately report B as an empty-list parent. It is not: B disappears from the child-only table but its parent total remains 7. Preserve a separate parent report and apply the revenue policy there.

Check your solution

  • Actual child count is 2.
  • Expanded row count is 3.
  • Filtering children must not silently remove B from parent revenue.

16. Orders A=[pen], B=[] and C=None are expanded, then missing child values are filtered. Which parent IDs disappear and what must be retained?

Show hint

Capture source state before filtering.

Show worked solution

A remains with pen; B and C disappear from the child-only table. Retain a parent audit showing B was known empty and C was unknown, because the same filtering outcome does not make those source states equivalent.

Check your solution

  • Retained child parent is A.
  • B is empty and C is unknown in the parent audit.

17. Order A’s original list is [pen,book,pen]. After explode and regroup, specify the acceptance comparison.

Show hint

Order and repeated occurrences both matter.

Show worked solution

Regroup by order in source occurrence order and compare the recovered list exactly to [pen,book,pen]. A set comparison would lose the duplicate pen and ordering, so it is insufficient for this sequence contract.

Check your solution

  • Recovered list preserves both pen occurrences.
  • The exact order is pen,book,pen.

18. Orders A=[pen,book] total 20 and B=[pen] total 5 are exploded. Compare child count with the repeated total sum. Order B is cancelled and must be excluded; recompute eligible parent revenue and actual child count.

Show hint

Child count and order revenue describe different grains.

Show worked solution

There are three child occurrences, but the expanded total column sums to 20+20+5=45. Parent revenue is 20+5=25. Report the three children separately and use the parent table for revenue. Excluding B leaves A’s parent revenue 20 and its two children; the repeated expanded sum 40 is still not revenue.

Check your solution

  • Child count is 3.
  • Parent revenue is 25; expanded repeated sum is 45.
  • Eligible parent revenue is 20 with 2 children.

19. Source order IDs A,B have totals 10 and 15. An expanded report shows A twice and B once. Design a valid parent-total check.

Show hint

Recover one validated total per parent before summing.

Show worked solution

Confirm that repeated A rows all carry the same total 10, that B carries 15, and that A,B are the expected unique parents. Compare one validated value per parent with the source sum 25; do not simply sum all three expanded values.

Check your solution

  • The parent-level sum is 25.
  • Repeated A totals must agree before deduplication.

20. Orders A has items [pen,pen] and quantities [1,2] with total 9; B has an empty list and total 0. Design a reconciliation report.

Show hint

Preserve occurrence positions and separate empty placeholders from children.

Show worked solution

Jointly expand A’s equal-length lists into pen/1 and pen/2 with distinct positions; retain B as an empty-list parent with no actual child. Check two actual child rows, one placeholder, unique parent IDs and parent revenue 9. Do not deduplicate pen or sum repeated order totals.

Check your solution

  • A has two distinct item occurrences.
  • B has zero actual children and parent revenue remains 9.

Key takeaways

  • Exploding changes row grain and repeats other fields.
  • Calculate order-level metrics at order grain.
  • Test empty lists and preserve identifiers for reconciliation.
  • An empty list can produce a missing placeholder row.
  • Related list columns require matching lengths and a valid positional contract.
  • Order-level totals must not be summed once per exploded child.

Official references