Skip to main content
 首页 » 编程设计

python之Pandas 外部合并同一 DataFrame 的两个版本

2024年10月17日8birdshome

我想合并两个如下所示的数据框:

In[14]: test1=pd.DataFrame({'col1':[1,2,3, 
                                    6,4,5], 
                            'col2':['First','Second','Third', 
                                    'Sixth','Fourth','Fifth']}) 
test1 
Out[14]: 
 
   col1    col2 
0     1   First 
1     2  Second 
2     3   Third 
3     6   Sixth 
4     4  Fourth 
5     5   Fifth 

和

In[15]: test2=pd.DataFrame({'col1':[1,7,2, 
                                    3,4,5], 
                            'col2':['First','Seventh','Second', 
                                    'Third','Fourth','Fifth']}) 
test2 
Out[15]:  
 
   col1     col2 
0     1    First 
1     7  Seventh 
2     2   Second 
3     3    Third 
4     4   Fourth 
5     5    Fifth 

您可能会注意到,这些 DataFrame 几乎相同,但它们每个都有一个额外的行,而另一个行中没有(3 6 Sixth in test1 和 1 7 Seventh in test2).

我想以这样一种方式合并这些 DataFrame,即一个 DataFrame 中的任何额外行都被插入到另一个 DataFrame 中,尽可能靠近它们的原始位置。这是我希望得到的结果:

   col1     col2 
0     1    First 
1     7  Seventh 
2     2   Second 
3     3    Third 
4     6    Sixth 
5     4   Fourth 
6     5    Fifth 

我试过用

In[16]: pd.merge(test1, test2, how='outer', sort=False) 

这输出

Out[16]:  
 
   col1     col2 
0     1    First 
1     2   Second 
2     3    Third 
3     6    Sixth 
4     4   Fourth 
5     5    Fifth 
6     7  Seventh 

如您所见,test2 的第二行现在位于底部。调用 pd.merge(test2, test1, how='outer', sort=False) 会得到类似的结果,但 test1 的第四行在底部。坚持两个 DataFrame 中的条目顺序对我来说至关重要,所以这不是我想要的。

我也尝试过 update()、combine_first() 和 replace(),但它们提供了内连接或左连接.

如何让 pandas 做我想做的事?

请您参考如下方法:

您可以使用 concat其次是 drop_duplicates和 sort_index :

df = pd.concat([test2, test1]).drop_duplicates().sort_index() 

结果输出:

   col1     col2 
0     1    First 
1     7  Seventh 
2     2   Second 
3     3    Third 
3     6    Sixth 
4     4   Fourth 
5     5    Fifth 

如果您希望新 DataFrame 的索引是唯一的,请执行 reset_index最后:

df = pd.concat([test2, test1]).drop_duplicates().sort_index().reset_index(drop=True) 

它给出了一个唯一索引:

   col1     col2 
0     1    First 
1     7  Seventh 
2     2   Second 
3     3    Third 
3     6    Sixth 
4     4   Fourth 
5     5    Fifth