# Module 10: Merging and Joining Data ## Learning Objectives By the end of this module, you will be able to: - Combine DataFrames using `pd.merge()` with inner, outer, left, and right joins - Understand one-to-one, one-to-many, and many-to-many relationships - Use `.join()` for index-based merging - Concatenate datasets with `pd.concat()` - Append rows with `.append()` (deprecated) and `pd.concat()` - Handle overlapping columns and indices during combination --- ```{note} Real-world data is rarely contained in a single table. Merging and joining are essential skills for combining information from multiple sources into a unified dataset for analysis. ``` ## The `pd.merge()` Function `pd.merge()` is the primary workhorse for combining DataFrames based on common columns or indices. It follows SQL-style join semantics. ```python import pandas as pd import numpy as np # Two related tables customers = pd.DataFrame({ "CustomerID": [1, 2, 3, 4, 5], "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"], "City": ["New York", "London", "Paris", "Tokyo", "Sydney"], }) orders = pd.DataFrame({ "OrderID": [101, 102, 103, 104, 105], "CustomerID": [1, 2, 2, 4, 6], "Amount": [250, 450, 300, 700, 150], "Date": ["2024-01-15", "2024-02-20", "2024-03-10", "2024-04-05", "2024-05-01"], }) print("Customers:") print(customers) print("\nOrders:") print(orders) ``` ## Types of Joins ### Inner join Returns only rows with matching keys in both DataFrames. ```python inner = pd.merge(customers, orders, on="CustomerID", how="inner") print(inner) ``` ### Left join Returns all rows from the left DataFrame, with NaN for non-matching right rows. ```python left = pd.merge(customers, orders, on="CustomerID", how="left") print(left) ``` ### Right join Returns all rows from the right DataFrame, with NaN for non-matching left rows. ```python right = pd.merge(customers, orders, on="CustomerID", how="right") print(right) ``` ### Outer join (full outer) Returns all rows from both DataFrames, filling NaN where no match exists. ```python outer = pd.merge(customers, orders, on="CustomerID", how="outer") print(outer) ``` ```{tip} Think of the `how` parameter as: *which DataFrame's rows should I keep all of?* `"left"` keeps all left rows, `"right"` keeps all right rows, `"inner"` keeps only matches, and `"outer"` keeps everything. ``` ## Join Types Visualised | Join Type | Left Rows | Right Rows | Matched Only | |-----------|-----------|------------|--------------| | Inner | Only matched | Only matched | Yes | | Left | All | Only matched | No | | Right | Only matched | All | No | | Outer | All | All | No | ## Merging on Different Column Names ```python orders_alt = orders.rename(columns={"CustomerID": "CID"}) # Specify left and right columns merged = pd.merge(customers, orders_alt, left_on="CustomerID", right_on="CID", how="inner") print(merged) ``` ## Merging on Multiple Columns ```python df1 = pd.DataFrame({ "Year": [2020, 2020, 2021, 2021], "Quarter": ["Q1", "Q2", "Q1", "Q2"], "Revenue": [100, 120, 150, 130], }) df2 = pd.DataFrame({ "Year": [2020, 2020, 2021, 2021], "Quarter": ["Q1", "Q2", "Q1", "Q2"], "Expenses": [80, 90, 110, 100], }) # Merge on multiple key columns merged = pd.merge(df1, df2, on=["Year", "Quarter"], how="inner") print(merged) ``` ## Handling Overlapping Column Names When both DataFrames have columns with the same name (other than the join key), Pandas adds suffixes. ```python df_a = pd.DataFrame({"ID": [1, 2, 3], "Value": [10, 20, 30], "Source": ["A", "A", "A"]}) df_b = pd.DataFrame({"ID": [2, 3, 4], "Value": [25, 35, 45], "Source": ["B", "B", "B"]}) # Custom suffixes merged = pd.merge(df_a, df_b, on="ID", how="outer", suffixes=("_left", "_right")) print(merged) ``` ```{warning} Always specify suffixes explicitly when merging DataFrames that share column names. The default suffixes `_x` and `_y` are not descriptive and can lead to confusion. ``` ## Index-Based Merge with `.join()` `.join()` combines DataFrames based on their index labels. ```python df_index = customers.set_index("CustomerID") orders_index = orders.set_index("CustomerID") # Join on index joined = df_index.join(orders_index, how="inner") print(joined) ``` ### Joining on index with a column from another ```python # Mix index and column joins result = customers.set_index("CustomerID").join( orders.set_index("CustomerID"), how="left", ) print(result) ``` ## `pd.concat()` — Concatenating Along an Axis ### Row-wise concatenation (stacking) ```python q1 = pd.DataFrame({"Product": ["A", "B"], "Sales": [100, 150]}) q2 = pd.DataFrame({"Product": ["A", "B"], "Sales": [120, 140]}) q3 = pd.DataFrame({"Product": ["A", "B", "C"], "Sales": [130, 160, 90]}) # Stack rows yearly = pd.concat([q1, q2, q3], ignore_index=True) print(yearly) ``` ### Column-wise concatenation ```python sales_2023 = pd.DataFrame({"Product": ["A", "B", "C"], "Sales_2023": [400, 450, 300]}) sales_2024 = pd.DataFrame({"Product": ["A", "B", "C"], "Sales_2024": [480, 520, 350]}) combined = pd.concat([sales_2023, sales_2024], axis=1) print(combined) ``` ### Handling index labels ```python # With keys to identify source combined = pd.concat( [q1, q2, q3], keys=["Q1", "Q2", "Q3"], names=["Quarter", "Index"], ) print(combined) ``` ```{tip} Use `keys` with `pd.concat()` to create a MultiIndex that tracks which source each row came from — invaluable for traceability. ``` ## Appending Data While `df.append()` is deprecated, the same functionality is achieved with `pd.concat()`. ```python # Old way (deprecated): # df1.append(df2) # Modern equivalent: result = pd.concat([df1, df2], ignore_index=True) ``` ```{warning} Pandas deprecated `.append()` in version 1.4.0 and removed it in 2.0. Always use `pd.concat()` for appending rows. ``` ## One-to-Many and Many-to-Many Relationships ### One-to-many merge ```python # One customer → many orders customer_orders = pd.merge(customers, orders, on="CustomerID", how="inner") print(f"One-to-many result shape: {customer_orders.shape}") print(customer_orders) ``` ### Many-to-many merge ```python # Products and categories (many-to-many) products = pd.DataFrame({"Product": ["A", "B", "C"], "Price": [10, 20, 30]}) categories = pd.DataFrame({ "Product": ["A", "A", "B", "C", "C", "C"], "Category": ["X", "Y", "X", "X", "Y", "Z"], }) result = pd.merge(products, categories, on="Product", how="inner") print(result) ``` ```{note} A many-to-many merge produces the Cartesian product of matching keys. Be cautious — if not expected, it can blow up the result size dramatically. ``` ## Validating Merge Relationships ```python # Use validate to check merge assumptions try: pd.merge(customers, orders, on="CustomerID", how="inner", validate="one_to_one") except pd.errors.MergeError as e: print(f"Validation error: {e}") # This will work (one customer can have many orders) pd.merge(customers, orders, on="CustomerID", how="inner", validate="one_to_many") ``` ## Practical Example: Sales Data Warehouse ```python # Simulate a star-schema data warehouse np.random.seed(42) # Dimension tables products = pd.DataFrame({ "ProductID": range(1, 6), "ProductName": ["Widget", "Gadget", "Doohickey", "Thingamajig", "Whatsit"], "Category": ["Tools", "Electronics", "Tools", "Electronics", "Misc"], }) stores = pd.DataFrame({ "StoreID": ["S01", "S02", "S03"], "StoreName": ["Downtown", "Uptown", "Midtown"], "City": ["New York", "Los Angeles", "Chicago"], }) # Fact table transactions = pd.DataFrame({ "TransactionID": range(1, 101), "ProductID": np.random.randint(1, 6, 100), "StoreID": np.random.choice(["S01", "S02", "S03"], 100), "Quantity": np.random.randint(1, 10, 100), "Price": np.round(np.random.uniform(5, 100, 100), 2), "Date": pd.date_range("2024-01-01", periods=100, freq="D"), }) # Build the star-schema query enriched = ( transactions .merge(products, on="ProductID", how="left") .merge(stores, on="StoreID", how="left") ) # Category sales by city report = enriched.groupby(["City", "Category"])["Quantity"].sum().unstack(fill_value=0) print(report) ``` ## Summary - `pd.merge()` provides SQL-style joins (inner, left, right, outer) based on common columns - Use `left_on`/`right_on` when key columns have different names - Merge on multiple keys by passing a list to `on` - `.join()` is a convenience method for index-based merges - `pd.concat()` stacks DataFrames row-wise (axis=0) or column-wise (axis=1) - Use `suffixes` to disambiguate overlapping column names - Validate merge cardinality with the `validate` parameter ## Exercises Using these DataFrames: ```python import pandas as pd import numpy as np employees = pd.DataFrame({ "EmpID": [101, 102, 103, 104, 105], "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"], "DeptID": [10, 20, 10, 30, 20], }) departments = pd.DataFrame({ "DeptID": [10, 20, 30, 40], "DeptName": ["Engineering", "Marketing", "Sales", "HR"], "Budget": [500000, 300000, 400000, 200000], }) salaries = pd.DataFrame({ "EmpID": [101, 102, 103, 104, 106], "Salary": [75000, 65000, 82000, 70000, 55000], "Bonus": [5000, 3000, 6000, 4000, 2000], }) ``` 1. Merge employees with departments to show each employee's department name 2. Merge employees with salaries using a left join — who is missing salary data? 3. Perform a full outer join of employees and salaries — which employees have no salary record and which salaries have no employee? 4. Concatenate a list of DataFrames `[q1_sales, q2_sales, q3_sales, q4_sales]` into a single yearly DataFrame with a `Quarter` key column 5. Use `.join()` to merge `employees.set_index("EmpID")` with `salaries.set_index("EmpID")` 6. Create a report showing average salary by department using merges and groupby ## Further Reading - [Pandas Merge Documentation](https://pandas.pydata.org/docs/user_guide/merging.html) - [SQL Join Visualizer](https://joins.spathon.com/) - [Pandas Concat Reference](https://pandas.pydata.org/docs/reference/api/pandas.concat.html)