Lesson 17 of 23
โฎPrev Nextโฏ

PY-401 ยท Summarising and joining

merge and join

โฑ 9 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

17of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    merge combines two tables by matching values in a shared column, like a SQL JOIN or an Excel VLOOKUP. orders.merge(customers, on="customer_id") adds each customer's name to their orders. how="inner" (the default) keeps only matches, how="left" keeps every row of the left table, and pd.concat stacks tables on top of each other.

    • Join two tables on a key column
    • Choose inner or left join
    • Stack tables with concat

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    merge and join, running
    1. import pandas as pd
    2. orders = pd.DataFrame({
    3. "order_id": [1, 2, 3, 4],
    4. "customer_id": [10, 20, 10, 30],
    5. "amount": [250, 90, 120, 400],
    6. })
    7. customers = pd.DataFrame({
    8. "customer_id": [10, 20, 40],
    9. "name": ["Asha", "Ben", "Dina"],
    10. })
    11. print(orders.merge(customers, on="customer_id"))
    12. print(orders.merge(customers, on="customer_id", how="left"))
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemThe orders table has customer numbers, and the customer table has names. The report needs names next to amounts. In Excel that is a VLOOKUP per row. In pandas it is one merge.
    2. The Python idealeft.merge(right, on="key")merge combines two tables by matching values in a shared column, like a SQL JOIN or an Excel VLOOKUP.
    3. In real lifeAn online shop merges the orders table with the products table on product_id to get each order's category, then groups by category for the weekly report.

    Start with a question

    The orders table has customer numbers, and the customer table has names. The report needs names next to amounts. In Excel that is a VLOOKUP per row. In pandas it is one merge.

    Data lives in separate tables: orders, customers, products. Almost every real analysis joins two or more of them.

    Explain it like I'm 10

    Two lists: one says "ticket 10 ordered pizza", the other says "ticket 10 is Asha". Match the ticket numbers and you know Asha ordered pizza.

    The technical explanation

    left.merge(right, on="key") matches rows where the key is equal. Use left_on and right_on when the names differ.

    how="inner" keeps only keys found in both tables. how="left" keeps every left row and fills NaN where the right table has no match. "right" and "outer" also exist.

    An order for customer 30 disappears in an inner join because customer 30 is not in the customer table. A left join keeps it with NaN for the name.

    pd.concat([a, b], ignore_index=True) stacks tables with the same columns, such as January and February exports.

    how=KeepsLike in SQL
    "inner"Only keys in both tablesINNER JOIN
    "left"Every left row, NaN where no matchLEFT JOIN
    "outer"Every row from bothFULL OUTER JOIN

    Syntax

    left.merge(right, on="key")
    left.merge(right, on="key", how="left")
    pd.concat([a, b], ignore_index=True)

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    An online shop merges the orders table with the products table on product_id to get each order's category, then groups by category for the weekly report.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What does merge do?
    2. 2. Which keeps every row of the left table?
    3. 3. An order has a customer_id that is not in customers. With the default merge itโ€ฆ
    4. 4. Which stacks January and February tables?
    5. 5. After a merge you have more rows than before. Likely cause?

    Questions people ask

    What is the difference between merge and join in pandas?

    merge joins on columns and is the general tool. join is a shortcut that joins on the index by default. Both can do inner, left, right and outer joins.

    How do I merge on columns with different names?

    Use left_on and right_on, for example orders.merge(customers, left_on="cust", right_on="customer_id"). You can drop the extra key column afterwards.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner What is the difference between merge and join in pandas?

    merge joins on columns and is the general tool. join is a shortcut that joins on the index by default. Both can do inner, left, right and outer joins.

    beginner How do I merge on columns with different names?

    Use left_on and right_on, for example orders.merge(customers, left_on="cust", right_on="customer_id"). You can drop the extra key column afterwards.

    intermediate What does merge do?

    Combines tables by matching a key column. merge matches rows on equal key values.

    intermediate Which keeps every row of the left table?

    how="left". A left join keeps all left rows.

    Quick revision

    Remember

    • Join two tables on a key column
    • Choose inner or left join
    • Stack tables with concat
    • After a merge, check the row count. If it grew, the key repeats on both sides. validate="many_to_one" makes pandas raise an error instead of silently duplicating rows.

    Syntax

    left.merge(right, on="key")
    left.merge(right, on="key", how="left")
    pd.concat([a, b], ignore_index=True)

    Official documentation