Left- und Right-Joins
Führen Sie Left- und Right-Joins aus, um alle Zeilen einer Tabelle zu erhalten und passende Datensätze aus einer anderen Tabelle zu übernehmen.
Left- und Right-Joins ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Pandas & NumPy Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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 nameLeft 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 HomeRight 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 differsComparing 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 HomeLeft 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 NaNPreserving 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 fewerQuick 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.
Häufig gestellte Fragen
Ist die Lektion „Left- und Right-Joins“ kostenlos?
Ja — der vollständige Text von „Left- und Right-Joins“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Pandas & NumPy Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Left- und Right-Joins“?
Führen Sie Left- und Right-Joins aus, um alle Zeilen einer Tabelle zu erhalten und passende Datensätze aus einer anderen Tabelle zu übernehmen. Du übst Pandas & NumPy Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Pandas & NumPy Academy zu starten?
Keine Vorkenntnisse erforderlich. Pandas & NumPy Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.
Wie lange dauert die Lektion „Left- und Right-Joins“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Pandas & NumPy Academy-Lektion Code schreiben und ausführen?
Ja. Jede Pandas & NumPy Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- pd.concat zum Stapeln von DataFrames
- pd.merge: Inner- und Outer-Joins
- Left- und Right-Joins
- Über den Index verknüpfen