w3resource

Merging DataFrames on their Indexes in Pandas


7. Merge on Index

Write a Pandas program to merge two DataFrames on their indexes.

This exercise demonstrates how to merge two DataFrames on their indexes using the left_index and right_index options.

Sample Solution :

Code :

import pandas as pd

# Create two sample DataFrames with indexes
df1 = pd.DataFrame({
    'Name': ['Selena', 'Annabel', 'Caeso'],
    'Age': [25, 30, 22]
}, index=[1, 2, 3])

df2 = pd.DataFrame({
    'Salary': [50000, 60000, 70000]
}, index=[1, 2, 3])

# Merge the DataFrames on their indexes
merged_df = pd.merge(df1, df2, left_index=True, right_index=True)

# Output the result
print(merged_df)

Output:

      Name  Age  Salary
1   Selena   25   50000
2  Annabel   30   60000
3    Caeso   22   70000            

Explanation:

  • Created two DataFrames df1 and df2, both with an index column.
  • Used pd.merge() with left_index=True and right_index=True to merge on the index.
  • The result is a DataFrame that merges rows based on their index values.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to merge two DataFrames on their indexes and then reset the index of the resulting DataFrame.
  • Write a Pandas program to merge two DataFrames on their indexes and handle missing index labels by filling them with a default value.
  • Write a Pandas program to merge two DataFrames on their indexes and sort the resulting DataFrame by the index.
  • Write a Pandas program to merge two DataFrames on their indexes and compute a new column that combines values from both original DataFrames.

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.