Pandas How To Uncategorized How to join two dataframes on key

How to join two dataframes on key

You can join two pandas DataFrames on a common key column by specifying the key column in the on parameter of the merge method.

Here’s an example of how to perform an inner join on two DataFrames based on a column named key:

import pandas as pd

df1 = pd.DataFrame({'key': [1, 2, 3, 4, 5], 'col1': [10, 20, 30, 40, 50]})
df2 = pd.DataFrame({'key': [2, 4, 6, 8, 10], 'col2': [100, 200, 300, 400, 500]})

result = pd.merge(df1, df2, on='key', how='inner')

In this example, the on parameter is set to ‘key’ to specify that the join should be based on the key column. The how parameter is set to ‘inner’ to specify that an inner join should be performed.

The result of the join will be a new DataFrame that contains only the rows where there is a match in both input DataFrames on the key column. In this example, the result will have three columns: key, col1, col2.

See also:
How to join two dataframes on multiple columns
How to join two dataframes
How to join two dataframes on index

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post