w3resource

Merging DataFrames using join() on Index in Pandas


Pandas: Custom Function Exercise-11 with Solution


Write a Pandas program to merge DataFrames using join() on Index.

In this exercise, we have used join() to merge two DataFrames on their index, which is a more concise alternative to merge() for index-based joining.

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])

# Perform a join on the indexes
joined_df = df1.join(df2)

# Output the result
print(joined_df)

Output:

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

Explanation:

  • Created two DataFrames df1 and df2 with a shared index.
  • Used the join() method to merge based on the index.
  • The result merges both DataFrames based on their index.

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.