Merging Pandas dataframes using inner and left joins

Here are examples of merging Pandas DataFrames using inner joins and left joins. Let's start by creating the dataframes and data in them.

import pandas as pd

# Create the first DataFrame
df1 = pd.DataFrame({'ID': [1, 2, 3, 4, 5],
                    'Name': ['John', 'Alice', 'Bob', 'Charlie', 'Eve']})

# Create the second DataFrame
df2 = pd.DataFrame({'ID': [2, 3, 4, 6, 7],
                    'Age': [25, 32, 47, 31, 19]})

# Print the first DataFrame
print("DataFrame 1:")
print(df1)
print()

# Print the second DataFrame
print("DataFrame 2:")
print(df2)
print()

Output:

DataFrame 1:
   ID     Name
0   1     John
1   2    Alice
2   3      Bob
3   4  Charlie
4   5      Eve

DataFrame 2:
   ID  Age
0   2   25
1   3   32
2   4   47
3   6   31
4   7   19

Now, let's perform the inner join and left join operations.

Inner Join

An inner join returns only the matching rows between two DataFrames based on a common column.

# Perform the inner join
inner_join_df = pd.merge(df1, df2, on='ID', how='inner')

# Print the inner join DataFrame
print("Inner Join:")
print(inner_join_df)

Output:

Inner Join:
   ID   Name  Age
0   2  Alice   25
1   3    Bob   32
2   4    Eve   47

Left Join

A left join returns all the rows from the left DataFrame and the matching rows from the right DataFrame. If there is no match, it returns NaN values.

# Perform the left join
left_join_df = pd.merge(df1, df2, on='ID', how='left')

# Print the left join DataFrame
print("Left Join:")
print(left_join_df)

Output:

Left Join:
   ID     Name   Age
0   1     John   NaN
1   2    Alice  25.0
2   3      Bob  32.0
3   4  Charlie  47.0
4   5      Eve   NaN

In the left join example, notice that the resulting DataFrame contains all the rows from df1 and the matching rows from df2. The Age column for non-matching rows is filled with NaN values.

I hope this helps! Let me know if you have any further questions.