Home  >  Article  >  Backend Development  >  How to Merge DataFrames Based on Their Indices?

How to Merge DataFrames Based on Their Indices?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 15:48:02368browse

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>
  • join: Perform a left join by default.
<code class="python">df1.join(df2)</code>
  • concat: Perform an outer join by default.
<code class="python">pd.concat([df1, df2], axis=1)</code>

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>

Default Inner Join:

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

Output:

   a  b  c   d
a  0  5  0  10
b  1  3  1  20

Default Left Join:

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

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

Default Outer Join:

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

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

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!

Statement:
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