How to Merge DataFrames Based on Their Indices?

Patricia Arquette
Release: 2024-10-31 15:48:02
Original
383 people have browsed it

How to Merge DataFrames Based on Their Indices?

Merging DataFrames by Index

Introduction

Merging dataframes is a common task in data analysis to combine information from multiple sources. Typically, merging is performed using columns as matching criteria. However, there are cases where you may need to merge dataframes based on their indices. This article provides guidance on how to accomplish that.

Merging Dataframes by Index Using Join Methods

To merge dataframes by index, you can use the following join methods:

  • merge: Perform an inner join by default.
<code class="python">pd.merge(df1, df2, left_index=True, right_index=True)</code>
Copy after login
  • join: Perform a left join by default.
<code class="python">df1.join(df2)</code>
Copy after login
  • concat: Perform an outer join by default.
<code class="python">pd.concat([df1, df2], axis=1)</code>
Copy after login

Examples

Consider the following dataframes:

<code class="python">df1 = pd.DataFrame({'a':range(6), 'b':[5,3,6,9,2,4]}, index=list('abcdef'))
df2 = pd.DataFrame({'c':range(4), 'd':[10,20,30, 40]}, index=list('abhi'))</code>
Copy after login

Default Inner Join:

<code class="python">df3 = pd.merge(df1, df2, left_index=True, right_index=True)</code>
Copy after login

Output:

   a  b  c   d
a  0  5  0  10
b  1  3  1  20
Copy after login

Default Left Join:

<code class="python">df4 = df1.join(df2)</code>
Copy after login

Output:

   a  b    c     d
a  0  5  0.0  10.0
b  1  3  1.0  20.0
c  2  6  NaN   NaN
d  3  9  NaN   NaN
e  4  2  NaN   NaN
f  5  4  NaN   NaN
Copy after login

Default Outer Join:

<code class="python">df5 = pd.concat([df1, df2], axis=1)</code>
Copy after login

Output:

     a    b    c     d
a  0.0  5.0  0.0  10.0
b  1.0  3.0  1.0  20.0
c  2.0  6.0  NaN   NaN
d  3.0  9.0  NaN   NaN
e  4.0  2.0  NaN   NaN
f  5.0  4.0  NaN   NaN
h  NaN  NaN  2.0  30.0
i  NaN  NaN  3.0  40.0
Copy after login

The above is the detailed content of How to Merge DataFrames Based on Their Indices?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!