Performing a left join between two DataFrames in Pandas
Pandas: Custom Function Exercise-3 with Solution
Write a Pandas program that performs a left join of two DataFrames.
This exercise demonstrates a left join of two DataFrames, including all rows from the left DataFrame and matching rows from the right.
Sample Solution :
Code :
import pandas as pd
# Create two sample DataFrames
df1 = pd.DataFrame({
'ID': [1, 2, 3],
'Name': ['Selena', 'Annabel', 'Caeso']
})
df2 = pd.DataFrame({
'ID': [2, 3, 4],
'Age': [25, 30, 22]
})
# Perform a left join on the 'ID' column
left_joined_df = pd.merge(df1, df2, on='ID', how='left')
# Output the result
print(left_joined_df)
Output:
ID Name Age 0 1 Selena NaN 1 2 Annabel 25.0 2 3 Caeso 30.0
Explanation:
- Created two DataFrames df1 and df2.
- Used pd.merge() with how='left' to perform a left join.
- The result includes all rows from the left DataFrame and only the matching rows from the right DataFrame.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/pandas/pandas-perform-a-left-join-between-two-dataframes.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics