0Pricing
Pandas & NumPy Academy · Lesson

Left and Right Joins

Perform left and right joins to preserve all rows from one table while matching records from another.

Left and Right Joins is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Asymmetric Joins

Inner and outer joins treat both DataFrames symmetrically. But often you want to preserve all records from one table while enriching them with data from another. This is where left joins and right joins come in. These asymmetric joins are extremely common in analytics: keep all transactions, add product names where available; keep all users, add their last purchase date if they have one.

Left Join: Preserve All Left Rows

A left join (how='left') keeps every row from the left DataFrame. For rows that find a matching key in the right DataFrame, the right columns are filled with the matched values. For rows with no match, the right columns are filled with NaN. The row count of the result always equals the row count of the left DataFrame (assuming no duplicate keys).

import pandas as pd

orders = pd.DataFrame({
    'order_id': [1, 2, 3, 4],
    'customer_id': [101, 102, 101, 999],
    'amount': [250, 80, 320, 150]
})
customers = pd.DataFrame({
    'customer_id': [101, 102, 103],
    'name': ['Alice', 'Bob', 'Carol']
})

result = pd.merge(orders, customers, on='customer_id', how='left')
print(result)
# All 4 orders kept; order with customer_id=999 gets NaN for name

Left Join Result Structure

After a left join, rows from the left DataFrame that found no match in the right will have NaN in every column that came from the right table. You can use this to identify unmatched rows with a boolean filter on a right-table column, and to count how many left rows had no match — a useful data quality check.

result = pd.merge(orders, customers, on='customer_id', how='left')
print(result)
#    order_id  customer_id  amount   name
# 0         1          101     250  Alice
# 1         2          102      80    Bob
# 2         3          101     320  Alice
# 3         4          999     150    NaN  <- no matching customer

# Count unmatched
unmatched = result['name'].isna().sum()
print(f'{unmatched} orders have no customer record')

When to Use a Left Join

Left joins are appropriate when your left DataFrame is the primary table and the right table is supplementary. Common scenarios: enriching a fact table with a dimension table (orders + product names), adding optional metadata (users + profile data), or computing metrics for all records even when a lookup fails. In most analytics code, left joins are far more common than right joins.

# Realistic pattern: enrich all products with optional category data
products = pd.DataFrame({'sku': ['A1', 'B2', 'C3'], 'price': [10, 20, 15]})
categories = pd.DataFrame({'sku': ['A1', 'C3'], 'category': ['Tools', 'Home']})

# Keep all products; add category where available
enriched = pd.merge(products, categories, on='sku', how='left')
print(enriched)
#    sku  price category
# 0   A1     10    Tools
# 1   B2     20      NaN
# 2   C3     15     Home

Right Join: Preserve All Right Rows

A right join (how='right') is the mirror image of a left join: it keeps every row from the right DataFrame and fills with NaN for left-table columns where no match exists. A right join is less common because you can always achieve the same result by swapping the DataFrame arguments and using a left join instead, which is clearer to readers.

# Right join: keep all customers, attach orders where they exist
result = pd.merge(orders, customers, on='customer_id', how='right')
print(result)
# All 3 customers appear; Carol (103) has NaN for order_id and amount

# Equivalent left join (swap arguments):
result2 = pd.merge(customers, orders, on='customer_id', how='left')
# Same data, just column order differs

Comparing All Four Join Types

The four join types differ only in which rows from the unmatched side are preserved. inner: matched rows only. outer: all rows from both sides. left: all left rows. right: all right rows. For unmatched entries, columns from the absent side are filled with NaN. Choosing correctly is crucial to avoid silently dropping or duplicating records.

# Summary table
# how='inner'  : rows in BOTH tables
# how='left'   : ALL left rows  + matched right
# how='right'  : matched left   + ALL right rows
# how='outer'  : ALL left rows  + ALL right rows

# Test each
for how in ['inner', 'left', 'right', 'outer']:
    r = pd.merge(orders, customers, on='customer_id', how=how)
    print(f'{how}: {len(r)} rows')

Filling NaN in Left Join Results

After a left join, unmatched rows have NaN in right-table columns. You often want to fill these with sensible defaults — for example, 'Unknown' for a missing category or 0 for a missing count. Use fillna() on the result, or pass fill_value in arithmetic operations that follow the join.

result = pd.merge(products, categories, on='sku', how='left')
result['category'] = result['category'].fillna('Uncategorised')
print(result)
#    sku  price       category
# 0   A1     10          Tools
# 1   B2     20  Uncategorised
# 2   C3     15           Home

Left Anti-Join: Rows with No Match

A useful pattern not directly supported by how is the anti-join: keep only left rows that have NO match in the right table. Implement it with a left join using indicator=True, then filter for _merge == 'left_only'. This is perfect for finding orphaned records, new items not in a reference list, or transactions missing from a ledger.

# Anti-join: orders with no matching customer record
result = pd.merge(orders, customers, on='customer_id',
                  how='left', indicator=True)
unmatched_orders = result[result['_merge'] == 'left_only'].drop(columns='_merge')
print(unmatched_orders)
#    order_id  customer_id  amount  name
# 3         4          999     150   NaN

Preserving Row Count with Left Join

When the right DataFrame has unique keys, a left join is guaranteed to preserve the exact row count of the left table. However, if the right table has duplicate key values, the left join multiplies rows just like an inner join does. Always verify the output row count matches the left table's row count when you expect a one-to-many relationship.

# Right table has duplicate keys -> row multiplication
orders_small = pd.DataFrame({'id': [1, 2], 'amount': [100, 200]})
multi_customer = pd.DataFrame({
    'id': [1, 1],  # duplicate!
    'contact': ['Alice', 'Alice2']
})

result = pd.merge(orders_small, multi_customer, on='id', how='left')
print(len(result))  # 3 rows! order 1 appears twice
print(result)

Real-World Left Join Pattern

Here is a complete real-world workflow: start with a transaction log, left-join a product catalog to get names, then left-join a customer table to get names. Fill missing lookups with defaults. The left join chain ensures every transaction row is preserved even if the product or customer record is missing from the reference tables.

transactions = pd.DataFrame({
    'txn_id': [1, 2, 3],
    'cust_id': [10, 11, 99],
    'prod_id': [20, 21, 20],
    'total': [50, 30, 70]
})

custs = pd.DataFrame({'cust_id': [10, 11], 'cust_name': ['Alice', 'Bob']})
prods = pd.DataFrame({'prod_id': [20, 21], 'prod_name': ['Widget', 'Gadget']})

result = (
    transactions
    .merge(custs, on='cust_id', how='left')
    .merge(prods, on='prod_id', how='left')
)
print(result)

Left Join vs Inner Join Decision

The choice between left and inner join is a business logic decision: should you retain records that have no lookup match, or silently drop them? Use left join when missing lookups are acceptable and you want to retain all primary records. Use inner join when a missing lookup means the record is invalid and should be excluded from analysis. Always document which you chose and why.

# Left join: keep all transactions (some may have no product name)
result_left = pd.merge(transactions, prods, on='prod_id', how='left')
print('Left join rows:', len(result_left))   # same as transactions

# Inner join: only transactions with known product
result_inner = pd.merge(transactions, prods, on='prod_id', how='inner')
print('Inner join rows:', len(result_inner))  # may be fewer

Quick Check

Test your understanding of left and right joins from this lesson.

Lesson Recap

In this lesson you learned: left join preserves all rows from the left DataFrame, filling right columns with NaN for non-matches; right join is the mirror image; the anti-join pattern using indicator=True finds left rows with no right match; and the choice between left and inner join is a business logic decision. Next up we explore joining DataFrames on their index rather than a column.

Frequently asked questions

Is the “Left and Right Joins” lesson free?

Yes — the full text of “Left and Right Joins” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “Left and Right Joins”?

Perform left and right joins to preserve all rows from one table while matching records from another. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Left and Right Joins” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. pd.concat for Stacking DataFrames
  2. pd.merge: Inner and Outer Joins
  3. Left and Right Joins
  4. Joining on the Index
← Back to Pandas & NumPy Academy