Skip to content

DOC: Add example for multi-column joins using merge #62016

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions doc/source/getting_started/comparison/comparison_with_sql.rst
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,42 @@ column with another DataFrame's index.
indexed_df2 = df2.set_index("key")
pd.merge(df1, indexed_df2, left_on="key", right_index=True)

:meth:`~pandas.merge` also supports joining on multiple columns by passing a list of column names.

.. code-block:: sql

SELECT *
FROM df1_multi
INNER JOIN df2_multi
ON df1_multi.key1 = df2_multi.key1
AND df1_multi.key2 = df2_multi.key2;

.. ipython:: python

df1_multi = pd.DataFrame({
"key1": ["A", "B", "C", "D"],
"key2": [1, 2, 3, 4],
"value": np.random.randn(4)
})
df2_multi = pd.DataFrame({
"key1": ["B", "D", "D", "E"],
"key2": [2, 4, 4, 5],
"value": np.random.randn(4)
})
pd.merge(df1_multi, df2_multi, on=["key1", "key2"])

If the columns have different names between DataFrames, on can be replaced with left_on and
right_on.

.. ipython:: python

df2_multi = pd.DataFrame({
"key_1": ["B", "D", "D", "E"],
"key_2": [2, 4, 4, 5],
"value": np.random.randn(4)
})
pd.merge(df1_multi, df2_multi, left_on=["key1", "key2"], right_on=["key_1", "key_2"])

LEFT OUTER JOIN
~~~~~~~~~~~~~~~

Expand Down
Loading