merge() (Pandas)

pd.merge() combines two DataFrames by matching values in one or more key columns, exactly like a SQL JOIN. It is how you bring related tables together on shared keys.

Pandas

merge joins on the columns named in on (or left_on/right_on if the names differ). The how argument controls which rows survive: 'inner' (default) keeps only matching keys, 'left' keeps all left rows, 'right' keeps all right rows, and 'outer' keeps everything, filling gaps with NaN.

Watch out for the cardinality of your keys: if a key appears multiple times on both sides you get a many-to-many cross product, which can blow up the row count. The validate argument (e.g. 'one_to_many') makes pandas check and raise if the relationship isn't what you expect.

When you want to join on the index rather than columns, the DataFrame.join() method is a convenient shorthand around merge.

Syntax

pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None)

Examples

Python

import pandas as pd
left = pd.DataFrame({"id": [1, 2], "name": ["a", "b"]})
right = pd.DataFrame({"id": [1, 2], "score": [90, 80]})
print(pd.merge(left, right, on="id"))

Output:

   id name  score
0   1    a     90
1   2    b     80

Learn it in a lesson

See also

Back to the Dictionary