Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
How to merge dataframes in R ?
Next article icon

How to Merge Two Pandas DataFrames on Index

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Merging two pandas DataFrames on their index is necessary when working with datasets that share the same row identifiers but have different columns. The core idea is to align the rows of both DataFrames based on their indices, combining the respective columns into one unified DataFrame.

To merge two pandas DataFrames on their index, you can use the merge() function with  left_index and right_index parameters set to True. Alternatively, you can use the join() or concat() functions, which also support merging on index.

merging-two-pandas-dataframes-based-on-index
Merge Two Pandas DataFrames on Index

Merge Two Pandas DataFrames on Index

This merge() method will merge the two Dataframes with matching indexes. If you have two DataFrames with matching index labels, you can simply set left_index=True and right_index=True in the pd.merge() function to merge them.

  • Types of Joins: Pandas supports different join types for merging data, such as inner, outer, left, and right joins. By default, pd.merge() performs an inner join, meaning it keeps only the rows that have matching indices in both DataFrames. You can specify the join type with the how parameter.
  • Aligning Data: When merging on the index, each row in the resulting DataFrame aligns based on the index value rather than a specific column, making this approach ideal when your row labels are the critical point of reference.
Python
# import pandas module import pandas as pd  # join two dataframes with merge print(pd.merge(data1, data2, left_index=True, right_index=True)) 

Output:

Merge Two Pandas DataFrames on Index using merge()

2. Merging two Pandas DataFrames on Index using join()

By default, the join() method it performs a left join. In this case, all rows from the left DataFrame (df1) are kept, and matching rows from the right DataFrame (df2) are added.

Python
# import pandas module import pandas as pd  # create student  dataframe data1 = pd.DataFrame({'id': [1, 2, 3, 4],                       'name': ['manoj', 'manoja', 'manoji', 'manij']},                      index=['one', 'two', 'three', 'four'])   # create marks  dataframe data2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7],                       'marks': [98, 90, 78, 86, 78]},                       index=['one', 'two', 'three', 'siz', 'seven'])  # join two dataframes print(data1.join(data2)) 

Output:

Merge two Pandas DataFrames on Index using join() 

3. Merging Two Pandas DataFrames on Index using concat()

By default, concat() method performs an outer join by setting axis=1. This method includes all rows from both DataFrames, filling in missing values with NaN where there are no matches.

Python
# import pandas module import pandas as pd  # join two dataframes with concat print(pd.concat([data1, data2], axis=1)) 

Output:

Merging Two Pandas DataFrames on Index using concat()

Key Takeaways:

  • Merging on Index: Use merge(), join(), or concat() to merge two DataFrames based on their row indices.
  • Join Types: You can specify different join types (inner, outer, left, or right) depending on whether you want to keep only matching rows or include all rows from one or both DataFrames.
  • Flexibility: The merge() function is more flexible than join() and concat(), allowing for more complex merging operations like merging on both columns and indices simultaneously.

Recommended Article: Pandas Merging, Joining, and Concatenating


Next Article
How to merge dataframes in R ?

M

manojkumarreddymallidi
Improve
Article Tags :
  • Python
  • Python-pandas
  • Python pandas-dataFrame
Practice Tags :
  • python

Similar Reads

  • How to Join Pandas DataFrames using Merge?
    Joining and merging DataFrames is that the core process to start  out with data analysis and machine learning tasks. It's one of the toolkits which each Data Analyst or Data Scientist should master because in most cases data comes from multiple sources and files. In this tutorial, you'll how to join
    3 min read
  • How to Get the Common Index of Two Pandas DataFrames
    When working with large datasets in Python Pandas, having multiple DataFrames with overlapping or related data is common. In many cases, we may want to identify the common indices between two DataFrames to perform further analysis, such as merging, filtering, or comparison. This article will guide u
    5 min read
  • How to combine two DataFrames in Pandas?
    While working with data, there are multiple times when you would need to combine data from multiple sources. For example, you may have one DataFrame that contains information about a customer, while another DataFrame contains data about their transaction history. If you want to analyze this data tog
    3 min read
  • How to merge dataframes in R ?
    In this article, we will discuss how to perform inner, outer, left, or right joins in a given dataframe in R Programming Language. Functions Used merge() function is used to merge or join two tables. With appropriate values provided to specific parameters, we can create the desired join. Syntax: mer
    3 min read
  • How to Merge DataFrames of different length in Pandas ?
    Merging DataFrames of different lengths in Pandas can be done using the merge(), and concat(). These functions allow you to combine data based on shared columns or indices, even if the DataFrames have unequal lengths. By using the appropriate merge method (like a left join, right join, or outer join
    4 min read
  • How To Concatenate Two or More Pandas DataFrames?
    In real-world data the information is often spread across multiple tables or files. To analyze it properly we need to bring all that data together. This is where the pd.concat() function in Pandas comes as it allows you to combine two or more DataFrames in: Vertically (stacking rows on top of each o
    3 min read
  • How to Join Two DataFrame in Scala?
    Scala stands for scalable language. It is a statically typed language although unlike other statically typed languages like C, C++, or Java, it doesn't require type information while writing the code. The type verification is done at the compile time. Static typing allows us to build safe systems by
    5 min read
  • Joining two Pandas DataFrames using merge()
    The merge() function is designed to merge two DataFrames based on one or more columns with matching values. The basic idea is to identify columns that contain common data between the DataFrames and use them to align rows. Let's understand the process of joining two pandas DataFrames using merge(), e
    4 min read
  • Merge two Pandas dataframes by matched ID number
    In this article, we will see how two data frames can be merged based on matched ID numbers. Approach Create a first data frameCreate a second data frameSelect Column to be matchedMerge using the merge function Syntax : DataFrame.merge(parameters) Display result Given below are implementations to pro
    4 min read
  • How to Find Matching Rows in Two Pandas DataFrames
    Let's learn how to find matching rows in two dataframes using Pandas. Find Matching Rows Using merge()merge() function is one of the most commonly used methods for finding matching rows in two DataFrames. It performs a SQL-style inner join, returning rows where matching values exist in both DataFram
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences