w3resource

Merging DataFrames on their Indexes in Pandas

Pandas: Custom Function Exercise-7 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/python-exercises/pandas/pandas-merge-dataframes-on-their-indexes.php