w3resource

Performing a left join between two DataFrames in Pandas


3. Left Join Merge

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to perform a left join on two DataFrames and replace missing values from the right DataFrame with the left’s column median.
  • Write a Pandas program to perform a left join on two DataFrames and then verify that all rows from the left DataFrame are preserved.
  • Write a Pandas program to perform a left join on two DataFrames and sort the resulting DataFrame based on a column from the right DataFrame.
  • Write a Pandas program to perform a left join on two DataFrames and then group the merged result by a column from the left 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.



Follow us on Facebook and Twitter for latest update.