How do you merge or join two Pandas DataFrames on multiple columns? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you merge or join two Pandas DataFrames on multiple columns?"

message-square
0

Call pd.merge(left_df, right_df, on=["col_a", "col_b"], how="inner") (or pass left_on=[...] and right_on=[...] when the key columns have different names in each DataFrame) to combine two DataFrames using a composite key across multiple columns—specifying how="left", "right", "outer", or "inner" and validate="one_to_one" / "many_to_one" to catch unexpected duplicate key explosions.

Basic Example

import pandas as pd

orders = pd.DataFrame({
    "store_id": [1, 1, 2, 3],
    "sku": ["A10", "B20", "A10", "C30"],
    "qty": [5, 2, 8, 1],
})

prices = pd.DataFrame({
    "store_id": [1, 1, 2],
    "sku": ["A10", "B20", "A10"],
    "unit_price": [10.0, 25.0, 9.5],
})

# 1. Recommended: Merge on multiple shared column names (`on=[...]`)
merged = pd.merge(
    orders,
    prices,
    on=["store_id", "sku"],
    how="left",
    validate="many_to_one",
)
print(merged)
# Output:
#    store_id  sku  qty  unit_price
# 0         1  A10    5        10.0
# 1         1  B20    2        25.0
# 2         2  A10    8         9.5
# 3         3  C30    1         NaN

# 2. Different column names across DataFrames (`left_on` / `right_on`):
prices_renamed = prices.rename(columns={"store_id": "branch_id", "sku": "item_code"})
merged_diff = pd.merge(
    orders,
    prices_renamed,
    left_on=["store_id", "sku"],
    right_on=["branch_id", "item_code"],
    how="inner",
).drop(columns=["branch_id", "item_code"])

Key Details & Edge Cases

  • Dtypes must match across every join key column (ValueError or silent non-matches):
    • If "store_id" is int64 in orders and object/string in prices, pd.merge() raises ValueError: You are trying to merge on object and int64 columns. Align key dtypes explicitly before merging (df["store_id"] = df["store_id"].astype("int64")).
  • Guard against Cartesian row explosion with validate=:
    • If prices accidentally contains two rows for (store_id=1, sku="A10"), a standard merge silently multiplies matching rows in orders (many-to-many join). Passing validate="many_to_one" (or "one_to_one") immediately raises MergeError if duplicate keys violate your expected cardinality.
  • NaN values in multi-column join keys match each other in pd.merge():
    • Unlike SQL JOIN (where NULL != NULL), Pandas treats NaN == NaN as a valid match by default (dropna=False internally). If rows with NaN in any join key should not match, filter them out beforehand (df.dropna(subset=["store_id", "sku"])).
  • Handling overlapping non-key column names (suffixes=("_left", "_right")):
    • If both DataFrames contain a non-key column with the same name (such as "updated_at"), Pandas renames them to "updated_at_x" and "updated_at_y" by default. Pass explicit suffixes=("_order", "_price") so column names remain self-documenting.
  • Inspecting which rows matched vs. stayed unmatched (indicator=True):
    • Pass indicator=True to add a _merge categorical column ("both", "left_only", "right_only")—ideal for auditing missing lookups after an "outer" or "left" merge.

Comparison of Multi-Column Join & Lookup Methods in Pandas

Method Joins on Regular Columns Directly? Supports Different Left/Right Key Names? Built-in Cardinality Check (validate=)? Best Used When
pd.merge(df1, df2, on=[...], how=...) (Recommended) Yes Yes (left_on= / right_on=) Yes ("one_to_one", "many_to_one", etc.) General-purpose SQL-style joins on two or more columns with full control over join type and validation.
df1.merge(df2, on=[...], how=...) Yes Yes (left_on= / right_on=) Yes Fluent method-chaining pipelines (df1.query(...).merge(df2, on=[...])).
df1.join(df2, on=[...], how=...) Partial (df2 keys must be its MultiIndex) No (index levels of df2 must match on=) Yes (Pandas 1.5+) Joining multiple DataFrames whose lookup tables are already indexed by a MultiIndex.
pd.merge_asof(..., by=[...], on="ts") Yes (exact match on by=[...] + nearest on "ts") Yes (left_by= / right_by=) No Time-series or ordered-range lookups grouped by exact multi-column keys (e.g., ["ticker", "exchange"]).