Pandas How To Uncategorized How to join two dataframes on query

How to join two dataframes on query

You can join two pandas DataFrames on a specific column using the merge method in pandas. There are different types of joins, including inner join, outer join, left join, and right join.

Here’s an example of how to perform an inner join on two DataFrames based on a common column called 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')

The merge method takes two DataFrames as input and performs an inner join on the column specified by the on parameter. The how parameter is used to specify the type of join. In this example, the how parameter is set to ‘inner’ to perform an inner join.

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 two columns: key and col1, col2.

Tags:

Leave a Reply

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

Related Post