w3resource

Merging DataFrames using join() on Index in Pandas


11. Join on Index

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.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to join two DataFrames using join() on their indexes and then sort the result by a specified column.
  • Write a Pandas program to join DataFrames using join() on indexes and fill missing values with zeros.
  • Write a Pandas program to join two DataFrames using join() on indexes and then compute the difference between similarly named columns.
  • Write a Pandas program to join two DataFrames using join() on their indexes and then reindex the resulting DataFrame to a given range.

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.