0Pricing
Pandas & NumPy Academy · 课时

左连接与右连接

执行左连接和右连接,在匹配另一个表中的记录时保留其中一个表的全部行。

左连接与右连接 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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.

常见问题解答

「左连接与右连接」课时是免费的吗?

是的 — 「左连接与右连接」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。

「左连接与右连接」这节课中我会学到什么?

执行左连接和右连接,在匹配另一个表中的记录时保留其中一个表的全部行。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Pandas & NumPy Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「左连接与右连接」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?

能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 pd.concat 堆叠 DataFrames
  2. pd.merge:内连接与外连接
  3. 左连接与右连接
  4. 按索引连接
← 返回 Pandas & NumPy Academy