Pulse Data Hub

Pandas Merge and Join Explained with Real Data

A pandas merge combines two tables by matching values in a key column, the same idea as a SQL JOIN. It is simple until the row count changes and you do not know why. This guide uses two real tables, hourly weather for New York’s three airports and a list of 1,458 airports, to show every join type, how to check a merge before trusting it, and what a bad key does to your data.

The data comes from the nycflights13 project: weather.csv has 26,115 hourly rows for 2013 and airports.csv has one row per airport. Code was run with pandas 3.0.5. We want to know which airport had the most low-visibility hours, with its full name in the result.

Bar chart of hours with visibility below 1 at the three New York airports in 2013: JFK 193, Newark 96, LaGuardia 90.
Hours with visibility below 1, by airport, from hourly weather merged with airport names.

Look at both tables and their keys first

import pandas as pd, numpy as np

base = "https://raw.githubusercontent.com/tidyverse/nycflights13/main/data-raw/"
w = pd.read_csv(base + "weather.csv")
a = pd.read_csv(base + "airports.csv")
print(w.shape, a.shape)
print(sorted(w.origin.unique()))
print("airport code unique:", a.faa.is_unique)
print(a[a.faa.isin(["EWR", "JFK", "LGA"])][["faa", "name", "alt"]])

Output:

(26115, 15) (1458, 8)
['EWR', 'JFK', 'LGA']
airport code unique: True
     faa                 name  alt
460  EWR  Newark Liberty Intl   18
691  JFK  John F Kennedy Intl   13
786  LGA           La Guardia   22

The weather table identifies the airport by the three-letter code in origin (EWR, JFK, LGA). The airports table uses the same code in a column named faa, and every code in it is unique. That is the shape of a classic many-to-one relationship: many weather rows point to one airport row. Before any merge, check which column is the key on each side and whether it is unique where you expect it to be.

Pandas merge with different key names

m = w.merge(a, left_on="origin", right_on="faa", how="left")
print(m.shape)
print(m[["origin", "faa", "name", "temp"]].head(3))

Output:

(26115, 23)
  origin  faa                 name   temp
0    EWR  EWR  Newark Liberty Intl  39.02
1    EWR  EWR  Newark Liberty Intl  39.02
2    EWR  EWR  Newark Liberty Intl  39.02

The result has 26,115 rows, the same as the weather table, and 23 columns (15 + 8). Each hourly row now carries its airport’s name, altitude and location. When both tables use the same column name, on="key" is enough and the key appears once. With different names, as here, both columns stay, and you can drop the extra one. If non-key columns share a name in both tables, pandas adds suffixes _x and _y; pass suffixes=("", "_ap") to choose your own.

The four join types, on the same two tables

To see what how changes, we first summarise the weather per airport (3 rows) and then join that with the full airports table (1,458 rows).

s = w.groupby("origin").agg(
    hours=("temp", "size"),
    avg_wind=("wind_speed", "mean"),
    low_vis=("visib", lambda x: (x < 1).sum()),
    precip=("precip", "sum"),
).round(2).reset_index()
print(s)

for how in ["inner", "left", "right", "outer"]:
    r = a.merge(s, left_on="faa", right_on="origin", how=how)
    print(how, r.shape, "rows with weather:", r.origin.notna().sum())

Output:

  origin  hours  avg_wind  low_vis  precip
0    EWR   8703      9.46       96   43.88
1    JFK   8706     11.47      193   34.69
2    LGA   8706     10.62       90   38.14
inner (3, 13) rows with weather: 3
left (1458, 13) rows with weather: 3
right (3, 13) rows with weather: 3
outer (1458, 13) rows with weather: 3

Airports on the left, weather summary on the right. An inner join keeps only keys present in both tables, so 3 rows. A left join keeps all 1,458 airports and fills the weather columns with missing values for the 1,455 airports that have none. A right join keeps all 3 weather rows, and an outer join keeps everything from both sides, which here equals the left join because every weather key exists in the airports table. Which one is correct depends on the question: if you need “every airport, with weather if available”, use left; if you need “only airports with data”, use inner.

Check what happened with indicator

The indicator=True option adds a column that says where each row came from. It is the quickest way to see unmatched rows.

o = a.merge(s, left_on="faa", right_on="origin", how="outer", indicator=True)
print(o._merge.value_counts().to_dict())
final = s.merge(a[["faa", "name", "alt"]], left_on="origin", right_on="faa").drop(columns="faa")
print(final.sort_values("low_vis", ascending=False)[["origin", "name", "hours", "low_vis", "precip"]])

Output:

{'left_only': 1455, 'both': 3, 'right_only': 0}
  origin                 name  hours  low_vis  precip
1    JFK  John F Kennedy Intl   8706      193   34.69
0    EWR  Newark Liberty Intl   8703       96   43.88
2    LGA           La Guardia   8706       90   38.14

Of 1,458 rows, 3 matched on both sides and 1,455 existed only in the airports table, with nothing missing on the weather side. The answer to our question: John F Kennedy Intl had 193 hours with visibility below 1, Newark Liberty Intl 96 and La Guardia 90. JFK is also the windiest on average (11.47 against 9.46 at Newark and 10.62 at LaGuardia). I did not check the visibility units, so “below 1” is the raw value in the file. The merge only attached the names, and the counting was done in the groupby, which is covered in pandas groupby explained.

The row explosion: merging on a key that is not unique

The most expensive merge mistake is joining on a key that repeats on both sides. Every row on the left is paired with every matching row on the right. We can show it with the weather table itself: join hourly rows to hourly rows by airport, month and day.

dup = w.merge(w, on=["origin", "month", "day"])
print("rows before:", len(w), "after:", len(dup), "| multiplied by", round(len(dup) / len(w), 1))
print(w.groupby(["origin", "month", "day"]).size().describe()[["count", "mean", "max"]])

Output:

rows before: 26115 after: 624785 | multiplied by 23.9
count    1092.000000
mean       23.914835
max        24.000000
dtype: float64

26,115 rows became 624,785, a factor of 23.9. Each airport-day has about 24 hourly rows, and every one of them matched all 24 on the other side (24 × 24 = 576 per full day). Nothing raised an error. If you then summed a column, the total would be about 24 times too large. This is the same fan-out that inflated revenue to 20,848.62 instead of 2,328.60 in SQL for data analysis, and the cure is the same: know your key.

Make pandas check for you: validate

The validate argument tells pandas what relationship you expect and raises an error if the data disagrees. To test it, we add a duplicate JFK row to the airports table, the kind of mistake that appears when a lookup table is appended twice.

a_bad = pd.concat([a, a[a.faa == "JFK"]], ignore_index=True)
print("no validation:", w.merge(a_bad, left_on="origin", right_on="faa").shape[0], "rows (expected", len(w), ")")
try:
    w.merge(a_bad, left_on="origin", right_on="faa", validate="many_to_one")
except Exception as e:
    print(type(e).__name__, "-", str(e).splitlines()[0])

Output:

no validation: 34821 rows (expected 26115 )
MergeError - Merge keys are not unique in right dataset; not a many-to-one merge

Without validation the merge quietly returns 34,821 rows: all 8,706 JFK weather rows appeared twice, and 26,115 + 8,706 = 34,821. With validate="many_to_one" pandas stops with a MergeError saying the keys in the right table are not unique. Add validate to every merge in a script that you will run again; it costs nothing and turns silent corruption into a loud failure.

Keys that look the same but are not

low = a.assign(faa=a.faa.str.lower())
print("lowercase codes:", w.merge(low, left_on="origin", right_on="faa").shape[0], "rows matched")
x = pd.DataFrame({"k": [1, np.nan, 3], "v": [1, 2, 3]})
y = pd.DataFrame({"k": [1, np.nan], "w": [10, 20]})
print(x.merge(y, on="k"))

Output:

lowercase codes: 0 rows matched
     k  v   w
0  1.0  1  10
1  NaN  2  20

An inner merge on “JFK” versus “jfk” returns zero rows, since text keys are compared exactly. Clean text keys with str.strip() and str.upper() before merging (see how to clean and preprocess data). A second surprise: missing values in the key match each other in pandas, unlike SQL, where NULL never equals NULL. The row with NaN in x was paired with the NaN row in y. Drop or fill missing keys first if that is not what you want.

merge, join and concat: which one?

DataFrame.join is a shortcut for merging on the index, and it defaults to a left join. Setting the airport code as the index of both tables gives the same answer as before.

print(s.set_index("origin").join(a.set_index("faa")[["name", "alt"]]))

Output:

        hours  avg_wind  low_vis  precip                 name  alt
origin                                                            
EWR      8703      9.46       96   43.88  Newark Liberty Intl   18
JFK      8706     11.47      193   34.69  John F Kennedy Intl   13
LGA      8706     10.62       90   38.14           La Guardia   22

Use merge when you match on columns, join when keys are already in the index, and pd.concat to stack tables with the same columns on top of each other (rows) or side by side by position (columns). For more everyday pandas patterns, see the pandas cheat sheet.

The official reference is the pandas merge, join, concatenate and compare guide. The data comes from the nycflights13 repository. Not tested here: merge_asof, cross joins and merging on several non-unique keys with validate="many_to_many".

FAQ

What is the difference between merge and join in pandas?

merge matches on columns by default and offers every join type. join matches on the index by default and is a left join unless you say otherwise. Both end up in the same machinery.

Why does my pandas merge have more rows than before?

The key is probably duplicated on one or both sides. In our test an hourly table merged with itself grew 23.9 times, and one duplicated lookup row added 8,706 rows. Use validate to catch it.

How do I merge on columns with different names?

Use left_on and right_on, as in w.merge(a, left_on="origin", right_on="faa"). Drop the duplicate key column afterwards if you do not need it.

How do I find rows that did not match in a merge?

Use indicator=True and filter the _merge column for left_only or right_only. In our outer join, 1,455 airport rows were left_only.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights