Pandas Merging 101
Here is an example of how to use the pd.merge()
function to merge two DataFrames in pandas:
import pandas as pd
# Create two DataFrames
df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'],
'value': [1, 2, 3, 4]})
df2 = pd.DataFrame({'key': ['B', 'D', 'E', 'F'],
'value': [5, 6, 7, 8]})
# Use pd.merge() to merge the DataFrames on the 'key' column
merged_df = pd.merge(df1, df2, on='key')
print(merged_df)
Watch a video course
Python - The Practical Guide
This will output the following DataFrame:
key value_x value_y 0 B 2 5 1 D 4 6
Note that the value
columns from each DataFrame are now labeled as value_x
and value_y
to distinguish them in the merged DataFrame.