Reshaping and Joining Tables Safely
Convert wide tables to long, choose inner, left and outer joins, check row counts, and catch duplicate keys that silently multiply your totals.
Welcome back!
Step 1 of 11Learn
The join that created $180,000
An analyst joined 10,000 orders to the customer table to add each customer's region, then summed revenue by region. The total came to $3.18 million. The orders table alone said $3.00 million.
Nothing was wrong with either table on its own. But the customer table contained duplicate rows for about 600 customers, the same kind of near duplicates you met earlier, now turned into exact duplicates after cleaning emails. When a key appears twice on one side of a join, every matching row on the other side is copied twice. Orders from those customers were counted double, adding $180,000 of revenue that never existed.
Joins are where cleaning problems from different tables collide. Duplicate keys multiply rows. Keys with different formats ("00123" versus 123) fail to match and silently drop rows. Missing parents leave orphans. And because a join always "works" in the sense of producing a table, none of this raises an error.
This lesson covers the two structural operations you'll do constantly while cleaning, reshaping a table between wide and long forms and joining tables, along with the row-count checks that make them safe. The rule to carry with you: after every join, compare row counts and totals with what you expected.
Step 2 of 11Learn
Wide and long
The same data can be stored wide, with one column per period or category, or long, with one row per observation:
Wide
| store | jan | feb | mar |
|---|---|---|---|
| North | 410 | 395 | 455 |
| South | 380 | 402 | 362 |
Long
| store | month | sales |
|---|---|---|
| North | jan | 410 |
| North | feb | 395 |
| … | … | … |
Wide tables are compact and pleasant for people to read. Long tables are what analysis tools want: one column holds all the sales values, so you can filter by month, group by store, plot a line per store or join a calendar table on the month column. Adding April to a long table means adding rows; adding it to a wide table means changing the structure.
Turning wide into long is called melting, unpivoting or pivoting longer (pd.melt in pandas, UNPIVOT in some SQL dialects). The reverse is a pivot. When melting, the number of rows becomes the number of original rows times the number of melted columns, which is an easy check that nothing was lost.
Watch for wide headers that hide two variables, such as "sales_2024_q1". After melting, split that column into year and quarter, so each variable gets its own column again.
Step 3 of 11Practice · Work it out
A wide table has one row per store for 50 stores, plus 12 monthly sales columns. After melting it into a long table with columns store, month and sales, how many rows should it have?
Step 4 of 11Learn
Join types and what they do to unmatched rows
A join combines two tables by matching values in key columns. The four main types differ only in what happens to rows that don't find a match:
- Inner join: keeps only rows with a match on both sides. Unmatched rows from either table disappear.
- Left join: keeps every row of the left table; where there is no match, the right table's columns are filled with missing values.
- Right join: the mirror image, keeping every row of the right table.
- Full outer join: keeps every row from both tables, filling gaps on either side.
For cleaning and enrichment, the left join is the usual choice: you start from the table whose grain you care about, such as orders, and add information, such as customer region, without losing any orders. Unmatched orders then show up with a blank region, which you can count, instead of vanishing as they would in an inner join.
Before joining, make the keys comparable. Both columns should have the same type (text versus number is a classic failure), the same case and no stray spaces, and the same formatting of codes such as leading zeros. A join on "00123" versus 123 matches nothing, and the result looks like a table full of orphans.
Step 5 of 11Practice · Match the pairs
Match each join type to what it returns.
Tap an answer, then tap the place where it belongs (or drag it there).
- Inner join
- Left join
- Full outer join
- Anti-join
Step 6 of 11Learn
Row-count checks and duplicate keys
Every join has an expected result size, and checking it takes seconds.
If you left-join orders to customers and the customer key is unique, the result should have exactly as many rows as the orders table. More rows means some customer keys are duplicated: each extra copy duplicates the matching orders. This is called a fan-out or row explosion. Fewer rows is impossible for a left join, so if you see it, you probably used an inner join.
When both sides have duplicate keys, the join becomes many-to-many and the result size multiplies: a key appearing 3 times on the left and 4 times on the right produces 12 rows. That is almost never what you want.
Practical defenses:
- Check key uniqueness first on the side that should be unique.
- Compare row counts and a total (such as revenue) before and after the join.
- Declare the relationship where your tool allows it. In pandas,
merge(..., validate="many_to_one")raises an error if the right-side key is not unique. - Count unmatched rows after a left join by counting blanks in a right-side column that is never blank in the source.
These checks feel like extra work until the first time they catch a fan-out that would have doubled a number in a board report.
Step 7 of 11Practice · Work it out
An orders table contains 5 orders for customer 7. By mistake, the customers table lists customer 7 twice. After a left join of orders to customers, how many rows will customer 7 have?
Step 8 of 11Practice · Code challenge · Python
Write find_orphans(orders, customer_ids). orders is a list of dicts with "order_id" and "customer_id"; customer_ids is a list of known customer IDs. IDs may differ in formatting: compare them as text with surrounding spaces removed and leading zeros stripped (so 123, "123" and " 00123" all match). Return the sorted list of order_ids whose customer is not known.
find_orphans([{"order_id": 1, "customer_id": " 00123"}, {"order_id": 2, "customer_id": "555"}], [123, 777])find_orphans([{"order_id": 9, "customer_id": 42}, {"order_id": 3, "customer_id": "0042 "}], ["42"])find_orphans([{"order_id": 5, "customer_id": "8"}, {"order_id": 4, "customer_id": "9"}], [])
Step 9 of 11Note
Step 10 of 11Practice · What would you do?
What would you do?
After left-joining a sales table (80,000 rows, total $4.20 million) to a product table to add product categories, you get 83,400 rows and a total of $4.39 million. What is the most likely problem and the right fix?
Step 11 of 11Practice · Choose one
Before joining two tables on customer_id, you notice that one table stores it as text ("004512") and the other as a number (4512). What should you do?
Lesson complete!